-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem89.cpp
More file actions
56 lines (44 loc) · 1021 Bytes
/
problem89.cpp
File metadata and controls
56 lines (44 loc) · 1021 Bytes
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
#include <bits/stdc++.h>
using namespace std;
class AlchemistsFraction {
string formula;
public:
void readInput() {
cin >> formula;
}
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
string solve() {
int num = 0, den = 1;
int i = 0, n = formula.size();
while (i < n) {
int sign = 1;
if (formula[i] == '+' || formula[i] == '-') {
sign = (formula[i] == '+') ? 1 : -1;
i++;
}
int n1 = 0;
while (i < n && isdigit(formula[i])) {
n1 = n1 * 10 + (formula[i++] - '0');
}
i++; // skip '/'
int d1 = 0;
while (i < n && isdigit(formula[i])) {
d1 = d1 * 10 + (formula[i++] - '0');
}
num = num * d1 + sign * n1 * den;
den = den * d1;
int g = gcd(abs(num), den);
num /= g;
den /= g;
}
return to_string(num) + "/" + to_string(den);
}
};
int main() {
AlchemistsFraction solver;
solver.readInput();
cout << solver.solve() << endl;
return 0;
}