-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasic Calculator
More file actions
45 lines (45 loc) · 1.16 KB
/
Copy pathBasic Calculator
File metadata and controls
45 lines (45 loc) · 1.16 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
class Solution {
public:
int calculate(string s) {
int num = 0, res = 0;
int sign = 1;
stack<int> opera;
stack<int> intraRes;
for(auto& x: s)
{
if(x == ' ') continue;
if(isdigit(x))
{
num = num*10 + x - '0';
continue;
}
res += sign*num;
num = 0;
switch(x)
{
case '+':
sign = 1;
break;
case '-':
sign = -1;
break;
case '(':
opera.push(sign);
intraRes.push(res);
sign = 1;
res = 0;
num = 0;
break;
case ')':
if(!intraRes.empty())
res = intraRes.top() + opera.top()*res,
num = 0,
sign = 1,
intraRes.pop(),
opera.pop();
break;
}
}
return res + sign*num;
}
};