-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy path_592.java
59 lines (53 loc) · 1.45 KB
/
_592.java
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
/**
* LeetCode 592 - Fraction Addition and Subtraction
* <p>
* An straightforward solution
*/
public class _592 {
int ptr;
String s;
public String fractionAddition(String expression) {
ptr = 0;
s = expression;
long[] res = {0, 1};
while (ptr < s.length()) {
int sign = 1;
if (s.charAt(ptr) == '+') {
ptr++;
}
if (s.charAt(ptr) == '-') {
sign = -1;
ptr++;
}
long numerator = nextNumber();
ptr++; // skip '/'
long denominator = nextNumber();
res = add(res, new long[]{sign * numerator, denominator});
}
if (res[1] < 0) {
res[0] = -res[0];
res[1] = -res[1];
}
return res[0] + "/" + res[1];
}
private long[] add(long[] a, long[] b) {
long[] c = {a[0] * b[1] + a[1] * b[0], a[1] * b[1]};
if (c[0] == 0)
c[1] = 1;
else {
long gcd = gcd(c[0], c[1]); // It is fine even when gcd is negative...
c[0] /= gcd;
c[1] /= gcd;
}
return c;
}
private long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
private long nextNumber() {
long res = 0;
while (ptr < s.length() && Character.isDigit(s.charAt(ptr)))
res = res * 10 + s.charAt(ptr++) - '0';
return res;
}
}