-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmath.cpp
74 lines (61 loc) · 1.76 KB
/
math.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
72
73
74
/*
In the name of ALLAH
Author : Raashid Anwar
*/
#include <bits/stdc++.h>
using namespace std;
#define int int64_t
const int M1 = 998244353;
const int M2 = 1000000007;
mt19937 rng((uint64_t)chrono::steady_clock::now().time_since_epoch().count());
class math {
public :
int to_int(const string &s) {
int sign = 1, i = 0, ans = 0;
if (!(s[0] >= '0' && s[0] <= '9')) {
sign = (s[0] == '-'? -1: 1);
i = 1;
}
while (i < (int)s.size())
ans = (ans * 10 + s[i++] - '0');
ans *= sign;
return ans;
}
int get_val(const string& s) {
int n = s.size();
for (int i = 0; i < n; i++)
if (s[i] == '-' && i && s[i - 1] >= '0' && s[i - 1] <= '9')
return get_val(s.substr(0, i)) - get_val(s.substr(i + 1, n - i - 1));
for (int i = 0; i < n; i++)
if (s[i] == '+')
return get_val(s.substr(0, i)) + get_val(s.substr(i + 1, n - i - 1));
for (int i = 0; i < n; i++)
if (s[i] == '*')
return get_val(s.substr(0, i)) * get_val(s.substr(i + 1, n - i - 1));
for (int i = 0; i < n; i++)
if (s[i] == '/')
return get_val(s.substr(0, i)) / get_val(s.substr(i + 1, n - i - 1));
return to_int(s);
}
string evaluate(const string& s) {
int n = s.size();
for (int i = 0, j = 0; i < n; i++) {
if (s[i] == ')')
return s.substr(0, j) + to_string(get_val(s.substr(j + 1, i - j - 1))) + s.substr(i + 1, n - i - 1);
if (s[i] == '(')
j = i;
}
return to_string(get_val(s));
}
};
void solve() {
math a;
string s;
cin >> s;
cout << a.evaluate(s) << "\n";
}
int32_t main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
solve();
}