Skip to content

Commit 85af9b4

Browse files
authored
Create 592. Fraction Addition and Subtraction (#565)
2 parents 668e036 + c0210b4 commit 85af9b4

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
class Solution {
2+
struct frac_t {
3+
int above;
4+
int below;
5+
};
6+
7+
void getFracs(vector<frac_t> &fracs, string &expr) {
8+
int N = expr.length();
9+
int idx = 0;
10+
int sign = 1;
11+
12+
frac_t frac;
13+
int digit = 0;
14+
while (idx < N) {
15+
if (isdigit(expr[idx])) {
16+
digit = digit * 10 + (expr[idx] - '0');
17+
}
18+
else if (expr[idx] == '/') {
19+
frac.above = sign * digit;
20+
digit = 0;
21+
sign = 1;
22+
}
23+
else {
24+
frac.below = sign * digit;
25+
fracs.push_back(frac);
26+
27+
digit = 0;
28+
sign = expr[idx] == '+' ? 1 : -1;
29+
}
30+
31+
++idx;
32+
}
33+
34+
/* Add last frac to fracs */
35+
frac.below = sign * digit;
36+
fracs.push_back(frac);
37+
}
38+
39+
void addFrac(frac_t &result, frac_t toAdd) {
40+
if (result.below == 0) {
41+
result = toAdd;
42+
return ;
43+
}
44+
45+
/* Get the least common multiple */
46+
int below_lcm = lcm(result.below, toAdd.below);
47+
result.above *= below_lcm / result.below;
48+
toAdd.above *= below_lcm / toAdd.below;
49+
50+
/* Update result */
51+
result.above += toAdd.above;
52+
result.below = below_lcm;
53+
}
54+
55+
public:
56+
string fractionAddition(string expression) {
57+
vector<frac_t> fracs;
58+
getFracs(fracs, expression);
59+
60+
/* Frac Addition */
61+
frac_t result(0, 0);
62+
for (frac_t frac : fracs) {
63+
addFrac(result, frac);
64+
}
65+
66+
/* Simplify the result */
67+
if (result.above == 0) {
68+
return "0/1";
69+
}
70+
71+
/* Greatest common divisor */
72+
int result_gcd = gcd(result.above, result.below);
73+
result.above /= result_gcd;
74+
result.below /= result_gcd;
75+
76+
return to_string(result.above) + "/" + to_string(result.below);
77+
}
78+
};

0 commit comments

Comments
 (0)