0%

592. Fraction Addition and Subtraction

O(nlogx) x是最大的分母

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
class Solution {
public:
string fractionAddition(string expression) {
istringstream input(expression);
int a, b, n = 0, d = 1;
char c;
while (input >> a >> c >> b) { // 这个很牛逼!!!
n = n * b + a * d;
d *= b;
int g = gcd(abs(n), d); // 注意n为负数和0的情况
n /= g;
d /= g;
}
return to_string(n) + "/" + to_string(d);
}

int gcd(int a, int b) { // 不需要分大小
while (b > 0) {
int t = a % b;
a = b;
b = t;
}
return a;
}
};