-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path150_evalRPN.cpp
More file actions
57 lines (57 loc) · 1.35 KB
/
150_evalRPN.cpp
File metadata and controls
57 lines (57 loc) · 1.35 KB
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
53
54
55
56
57
class Solution {
public:
int stringToInt(string s){
int flag = 1,i = 0;
if(s[0] == '-'){
flag = -1;
i = 1;
}
int num = 0;
for(;i<s.size();i++){
num*=10;
num+=s[i]-'0';
}
return num*flag;
}
int calcSig(string s){
if(s == "+")
return 1;
if(s == "-")
return 2;
if(s == "*")
return 3;
if(s == "/")
return 4;
return 0;
}
int evalRPN(vector<string>& tokens) {
stack<int> nums;
int a,b;
for(string s:tokens){
int code = calcSig(s);
if(code == 0)
nums.push(stringToInt(s));
else{
a = nums.top();
nums.pop();
b = nums.top();
nums.pop();
switch(code){
case 1:
nums.push(b+a);
break;
case 2:
nums.push(b-a);
break;
case 3:
nums.push(b*a);
break;
case 4:
nums.push(b/a);
break;
}
}
}
return nums.top();
}
};