Skip to content

Create 592. Fraction Addition and Subtraction #565

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 23, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}
};
Loading