0592.cpp (1081B)
1 class Solution { 2 public: 3 string fractionAddition(const string &expression) const { 4 const int n = size(expression); 5 int numerator = 0, denominator = 1; 6 7 for (int i = 0; i < n;) { 8 int sign = 1; 9 if (expression[i] == '+' || expression[i] == '-') { 10 if (expression[i] == '-') sign = -1; 11 i++; 12 } 13 14 int num = 0; 15 while (i < n && isdigit(expression[i])) { 16 num = num * 10 + (expression[i] - '0'); 17 i++; 18 } 19 num *= sign; 20 21 i++; 22 23 int den = 0; 24 while (i < n && isdigit(expression[i])) { 25 den = den * 10 + (expression[i] - '0'); 26 i++; 27 } 28 29 numerator = numerator * den + num * denominator; 30 denominator *= den; 31 32 int gcdVal = gcd(abs(numerator), denominator); 33 numerator /= gcdVal; 34 denominator /= gcdVal; 35 } 36 37 return to_string(numerator) + "/" + to_string(denominator); 38 } 39 };