1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| class Solution { public int gcd(int x, int y){ if(y != 0){ return gcd(y, x%y); }else{ return x; } } public String fractionAddition(String expression) { expression = expression + "+"; int len = expression.length(); int[] down = new int[11]; int[] up = new int[11]; int sum = 1; int cnt = 0; int i = 0, j = 0, k = 0; int flag = 0; if(expression.charAt(0) == '-'){ i = 1; j = 3; k = 0; }else{ i = 0; j = 2; k = 3; flag = 1; }
int num1 = 0, num2 = 1; while( i < len && j < len && k < len){ char ch = ' '; if(flag == 1){ ch = '+'; k = -1; flag = 0; }else{ ch = expression.charAt(k); } if(expression.charAt(i+1) != '/'){ num1 = 10; i++; j++; k++; }else{ num1 = Integer.parseInt(expression.substring(i, i + 1)); } if(expression.charAt(j+1) != '+' && expression.charAt(j+1) != '-'){ num2 = 10; i++; j++; k++; }else { num2 = Integer.parseInt(expression.substring(j, j + 1)); } if(ch == '-'){ num1 = 0-num1; } up[cnt] = num1; down[cnt++] = num2; sum = sum * num2; i = i+4; j = j+4; k = k+4; } int resUp = 0; for(int a = 0; a < cnt; a++){ resUp += up[a] * (sum / down[a]); } int g = gcd(resUp, sum); if(g < 0) g = 0-g; return resUp/g + "/" + sum/g; } }
|