-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasic-calculator-ii.cpp
40 lines (40 loc) · 1.02 KB
/
basic-calculator-ii.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
class Solution {
public:
// 之前写的都太麻烦了,以后还是用这个吧:
// https://leetcode.com/problems/basic-calculator-ii/discuss/257497/Easy-read-c++-solution
// 并且记住规则:遇到+-进栈,遇到*/直接操作
int calculate(string s) {
char op;
int n;
istringstream ins("+"+s);
stack<int> st;
while(ins>>op>>n){
if(op=='+'){
st.push(n);
continue;
}
if(op=='-'){
st.push(-n);
continue;
}
if(op=='*'){
int tmp=st.top()*n;
st.pop();
st.push(tmp);
continue;
}
if(op=='/'){
int tmp=st.top()/n;
st.pop();
st.push(tmp);
continue;
}
}
int res=0;
while(!st.empty()){
res+=st.top();
st.pop();
}
return res;
}
};