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 /= 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; } };
|