-
Notifications
You must be signed in to change notification settings - Fork 0
/
BasicCalculator2.c++
48 lines (46 loc) · 1.18 KB
/
BasicCalculator2.c++
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
class Solution {
public:
int calculate(string s) {
stack<int> st;
int tmp(0), ans(0), num;
char op = '+';
int size = s.size();
for(char ch: s)
{
size--;
if(isdigit(ch))
{
tmp = tmp * 10 + (ch - '0');
}
if(!isdigit(ch) and !isspace(ch) || !size)
{
switch(op)
{
case '+':
st.push(tmp);
break;
case '-':
st.push(-tmp);
break;
case '*':
num = st.top();
st.pop();
st.push(num * tmp);
break;
default:
num = st.top();
st.pop();
st.push(num / tmp);
}
tmp = 0;
op = ch;
}
}
while (!st.empty())
{
ans += st.top();
st.pop();
}
return ans;
}
};