-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculate.cpp
More file actions
84 lines (82 loc) · 2.15 KB
/
calculate.cpp
File metadata and controls
84 lines (82 loc) · 2.15 KB
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
75
76
77
78
79
80
81
82
83
84
class Solution {
public:
inline int calc() {
int n1 = num.top();
num.pop();
int n2 = num.top();
num.pop();
char op = ops.top();
ops.pop();
switch (op) {
case '+':
return n1 + n2;
case '-':
return n2 - n1;
case '*':
return n1 * n2;
case '/':
return n2 / n1;
}
return 1;
}
int calculate(string s) {
stack<int>().swap(num);
stack<char>().swap(ops);
string a;
for (char c: s) {
if (c == ' ') continue;
if (c >= '0' && c <= '9') a += c;
else {
num.push(std::stoi(a));
a = "";
while (!ops.empty() && pri[c] >= pri[ops.top()]) num.push(calc());
ops.push(c);
}
}
num.push(std::stoi(a));
while (!ops.empty()) {
num.push(calc());
}
return num.top();
}
private:
stack<int> num;
stack<char> ops;
unordered_map<char, int> pri = {{'*', 1}, {'/', 1}, {'+', 2}, {'-', 2}};
};
class Solution {
public:
int calculate(string s) {
int n = s.size();
int curr = 0;
char sign = '+';
stack<int> st;
for (int i = 0; i < n; i++) {
char c = s[i];
if (isdigit(c)) curr = curr * 10 + (c - '0');
if ((!(c == ' ') and !isdigit(c)) or i == n - 1) {
switch (sign) {
case '+':
case '-':
curr = (sign == '+') ? curr : -curr;
st.push(curr);
break;
case '*':
case '/':
int a = st.top();
st.pop();
a = (sign == '*') ? a * curr : a / curr;
st.push(a);
}
sign = c;
curr = 0;
}
}
int res = 0;
while(!st.empty()) {
res += st.top();
st.pop();
}
return res;
}
};