-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution10.java
More file actions
49 lines (43 loc) · 1.42 KB
/
Solution10.java
File metadata and controls
49 lines (43 loc) · 1.42 KB
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
class Solution10 {
public String fractionAddition(String expression) {
long x = 0, y = 1;
int index = 0, n = expression.length();
while (index < n) {
long x1 = 0, sign = 1;
if (expression.charAt(index) == '-' || expression.charAt(index) == '+') {
sign = expression.charAt(index) == '+' ? 1 : -1;
index++;
}
while (index < n && Character.isDigit(expression.charAt(index))) {
x1 = x1 * 10 + expression.charAt(index) - '0';
index++;
}
x1 = sign * x1;
long y1 = 1;
if (index < n && expression.charAt(index) == '/') {
index++;
y1 = 0;
while (index < n && Character.isDigit(expression.charAt(index))) {
y1 = y1 * 10 + expression.charAt(index) - '0';
index++;
}
}
x = x * y1 + x1 * y;
y *= y1;
}
if (x == 0) {
return "0/1";
}
long g = gcd(Math.abs(x), Math.abs(y));
return Long.toString(x / g) + "/" + Long.toString(y / g);
}
public long gcd(long a, long b) {
long remainder = a % b;
while (remainder != 0) {
a = b;
b = remainder;
remainder = a % b;
}
return b;
}
}