-
Notifications
You must be signed in to change notification settings - Fork 0
/
224. 基本计算器.cc
48 lines (45 loc) · 1.32 KB
/
224. 基本计算器.cc
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
//40ms 11.3MB
class Solution {
public:
int calculate(string s)
{
stack<int> numberSta;
stack<char> operatorSta;
int size = s.size();
for(int i=0; i<size; ++i)
{
if(s[i] == ' ') continue;
else if(s[i] == '+' || s[i] == '-' || s[i] == '(')
{
operatorSta.push(s[i]);
}
else if(isdigit(s[i]))
{
int start = i;
while(i<size && isdigit(s[i])) ++i;
numberSta.push(stoi(s.substr(start, i-start)));
--i;
}
else if(s[i] == ')')
{
int sum = 0;
while(operatorSta.top() != '(')
{
char op = operatorSta.top(); operatorSta.pop();
int opn = numberSta.top(); numberSta.pop();
sum += op=='+'?opn:-opn;
}
numberSta.top() += sum;
operatorSta.pop();//()
}
}
int sum = 0;
while(!operatorSta.empty())
{
char op = operatorSta.top(); operatorSta.pop();
int opn = numberSta.top(); numberSta.pop();
sum += op=='+'?opn:-opn;
}
return sum + numberSta.top();
}
};