-
Notifications
You must be signed in to change notification settings - Fork 0
/
Basic Calculator.cpp
49 lines (47 loc) · 1.1 KB
/
Basic Calculator.cpp
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
class Solution {
public:
int calculate(string s) {
int result=0;
int sum=0;
int sign=1;
stack<int>st;
int n=s.size();
for(int i=0;i<n;i++)
{
if(isdigit(s[i]))
{
sum=s[i] -'0';
while(i+1<n && isdigit(s[i+1]))
{
sum = sum*10 + (s[i+1] -'0');
i++;
}
result+=sum*sign;
}
else if(s[i] == '+')
{
sign=1;
}
else if (s[i] == '-')
{
sign=-1;
}
else if (s[i] == '(')
{
st.push(result);
st.push(sign);
result=0;
sign=1;
}
else if(s[i] == ')')
{
int xsign=st.top();
st.pop();
int xresult= st.top();
st.pop();
result=result*xsign + xresult;
}
}
return result;
}
};