Skip to content

Commit

Permalink
Create 592. Fraction Addition and Subtraction (#565)
Browse files Browse the repository at this point in the history
  • Loading branch information
Chayandas07 authored Aug 23, 2024
2 parents 668e036 + c0210b4 commit 85af9b4
Showing 1 changed file with 78 additions and 0 deletions.
78 changes: 78 additions & 0 deletions 592. Fraction Addition and Subtraction
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
class Solution {
struct frac_t {
int above;
int below;
};

void getFracs(vector<frac_t> &fracs, string &expr) {
int N = expr.length();
int idx = 0;
int sign = 1;

frac_t frac;
int digit = 0;
while (idx < N) {
if (isdigit(expr[idx])) {
digit = digit * 10 + (expr[idx] - '0');
}
else if (expr[idx] == '/') {
frac.above = sign * digit;
digit = 0;
sign = 1;
}
else {
frac.below = sign * digit;
fracs.push_back(frac);

digit = 0;
sign = expr[idx] == '+' ? 1 : -1;
}

++idx;
}

/* Add last frac to fracs */
frac.below = sign * digit;
fracs.push_back(frac);
}

void addFrac(frac_t &result, frac_t toAdd) {
if (result.below == 0) {
result = toAdd;
return ;
}

/* Get the least common multiple */
int below_lcm = lcm(result.below, toAdd.below);
result.above *= below_lcm / result.below;
toAdd.above *= below_lcm / toAdd.below;

/* Update result */
result.above += toAdd.above;
result.below = below_lcm;
}

public:
string fractionAddition(string expression) {
vector<frac_t> fracs;
getFracs(fracs, expression);

/* Frac Addition */
frac_t result(0, 0);
for (frac_t frac : fracs) {
addFrac(result, frac);
}

/* Simplify the result */
if (result.above == 0) {
return "0/1";
}

/* Greatest common divisor */
int result_gcd = gcd(result.above, result.below);
result.above /= result_gcd;
result.below /= result_gcd;

return to_string(result.above) + "/" + to_string(result.below);
}
};

0 comments on commit 85af9b4

Please sign in to comment.