-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculate.cpp
More file actions
54 lines (54 loc) · 1.46 KB
/
calculate.cpp
File metadata and controls
54 lines (54 loc) · 1.46 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
class Solution {
public:
void calc(stack<int> &num, stack<char> &ops) {
char c = ops.top();
ops.pop();
int n1 = num.top();
num.pop();
int n2 = num.top();
num.pop();
if (c == '-') num.push(n2 - n1);
else num.push(n2 + n1);
}
int calculate(string s) {
stack<int> num;
stack<char> ops;
int d = 0;
char prev = '#';
for (char c: s) {
if (c == ' ')
continue;
if (std::isdigit(c)) {
d = d * 10 + static_cast<int>(c - '0');
}
else {
if (std::isdigit(prev)) {
num.push(d);
}
d = 0;
if (c == ')') {
while (ops.top() != '(') {
calc(num, ops);
}
ops.pop();
}
else if (c == '(') {
ops.push(c);
}
else { // + -
if (prev == '#' || prev == '(')
num.push(0);
if (!ops.empty() && (ops.top() == '-' || ops.top() == '+'))
calc(num, ops);
ops.push(c);
}
}
prev = c;
}
if (std::isdigit(prev)) num.push(d);
while (!ops.empty()) {
calc(num, ops);
}
return num.top();
}
};