-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.cpp
71 lines (58 loc) · 1.6 KB
/
Solution.cpp
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <algorithm>
#include <climits>
#include <functional>
#include <iostream>
#include <queue>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
class Solution {
private:
int euclidsGCD(int a, int b) {
if (b == 0) {
// if remainder is 0, return a which is the GCD
return a;
}
return euclidsGCD(b, a % b);
}
public:
string fractionAddition(string expression) {
int n = expression.length();
// Running result;
int numerator = 0;
int denominator = 1;
int i = 0;
while (i < n) {
int currNumerator = 0;
int currDenominator = 0;
// Parse the fraction
bool isNegative = false; // first '+' is omitted
if (expression[i] == '+' || expression[i] == '-') {
isNegative = expression[i] == '-';
++i;
}
while (isdigit(expression[i])) {
currNumerator = (currNumerator * 10) + (expression[i] - '0');
++i;
}
currNumerator = isNegative ? -currNumerator : currNumerator;
// Skip '/'
++i;
while (isdigit(expression[i])) {
currDenominator = (currDenominator * 10) + (expression[i] - '0');
++i;
}
// Add fractions together
numerator = (numerator * currDenominator) + (currNumerator * denominator);
denominator = denominator * currDenominator;
}
// Reduce the fractions, using their GCD
int gcd = abs(euclidsGCD(numerator, denominator));
numerator /= gcd;
denominator /= gcd;
return to_string(numerator) + '/' + to_string(denominator);
}
};