Skip to content

Commit b523b24

Browse files
authored
Create 224.Basic Calculator.cpp
1 parent aa5d69f commit b523b24

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class Solution {
2+
public:
3+
int calculate(string s)
4+
{
5+
stack<int>nums;
6+
stack<int>sign;
7+
s.insert(s.begin(),'+');
8+
9+
int curResult=0;
10+
for (int i=0; i<s.size(); i++)
11+
{
12+
if (s[i]=='(')
13+
{
14+
nums.push(curResult);
15+
curResult=0;
16+
sign.push(1);
17+
}
18+
else if (s[i]==')')
19+
{
20+
curResult*=sign.top();
21+
sign.pop();
22+
curResult+=nums.top();
23+
nums.pop();
24+
}
25+
else if (s[i]=='+')
26+
sign.push(1);
27+
else if (s[i]=='-')
28+
sign.push(-1);
29+
else if (s[i]>='0' && s[i]<='9')
30+
{
31+
int i0=i;
32+
while (i<s.size() && s[i]>='0' && s[i]<='9')
33+
i++;
34+
int num = stoi(s.substr(i0,i-i0));
35+
curResult+=sign.top()*num;
36+
sign.pop();
37+
i--;
38+
}
39+
}
40+
41+
return curResult;
42+
43+
}
44+
};

0 commit comments

Comments
 (0)