[LeetCode] Fraction Addition and Subtraction

592. Fraction Addition and Subtraction

Given a string expression representing an expression of fraction addition and subtraction, return the calculation result in string format.

The final result should be an irreducible fraction. If your final result is an integer, change it to the format of a fraction that has a denominator 1. So in this case, 2 should be converted to 2/1.

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
class Solution {
pair<int, int> parse(int& i, string& exp) {
int a = 0, b = 0;
bool neg = exp[i] == '-';
if(!isdigit(exp[i])) i++;
while(i < exp.length() and isdigit(exp[i])) {
a = a * 10 + (exp[i++] & 0b1111);
}
i++;
while(i < exp.length() and isdigit(exp[i])) {
b = b * 10 + (exp[i++] & 0b1111);
}
return {neg ? -a : a , b};
}
string helper(string exp) {
int a = 0, b = 1, i = 0;
while(i < exp.length()) {
auto [aa, bb] = parse(i, exp);

int lcm = b / gcd(b,bb) * bb;

a = lcm / b * a + lcm / bb * aa;

b = lcm;

int g = __gcd(a,b);
a /= g;
b /= g;
if(b < 0) {
b = -b;
a = -a;
}
}
if(a == 0) return "0";
if(b == 1) return to_string(a);
return to_string(a) + "/" + to_string(b);
}
public:
string fractionAddition(string expression) {
string res = helper(expression);
if(res == "0") return "0/1";
if(res.find('/') == string::npos) return res + "/1";
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/21/PS/LeetCode/fraction-addition-and-subtraction/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.