-
Notifications
You must be signed in to change notification settings - Fork 0
/
150. Evaluate Reverse Polish Notation.txt
52 lines (49 loc) · 1.35 KB
/
150. Evaluate Reverse Polish Notation.txt
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
50
51
52
https://leetcode.com/problems/evaluate-reverse-polish-notation/
class Solution {
private:
int toInt(string a){
int c = 0;
if(a[0] == '-'){
for(int i = 1; i < a.length(); i++){
c += (a[i] - '0') * pow(10,a.length() - 1 - i);
}
return -1*c;
}
for(int i = 0; i < a.length(); i++){
c += (a[i] - '0') * pow(10,a.length() - 1 - i);
}
return c;
}
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
int a,b;
for(int i = 0; i < tokens.size(); i++){
if(tokens[i] == "+"){
a = st.top();st.pop();
b = st.top();st.pop();
st.push(a+b);
}
else if(tokens[i] == "-"){
a = st.top();st.pop();
b = st.top();st.pop();
st.push(b-a);
}
else if(tokens[i] == "*"){
a = st.top();st.pop();
b = st.top();st.pop();
st.push(b*a);
}
else if(tokens[i] == "/"){
a = st.top();st.pop();
b = st.top();st.pop();
st.push(b/a);
}
else{
a = toInt(tokens[i]);
st.push(a);
}
}
return st.top();
}
};