-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path150. Evaluate Reverse Polish Notation.cpp
More file actions
53 lines (49 loc) · 1.35 KB
/
Copy path150. Evaluate Reverse Polish Notation.cpp
File metadata and controls
53 lines (49 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
class Solution {
public:
int str2int(string& str)
{
int res = 0;
int i = 0;
int flag = 1;
if (str[i] == '+')
i = 1;
else if (str[i] == '-')
{
i = 1;
flag = -1;
}
else
i = 0;
for (; i < str.size(); i++)
res = res * 10 + (str[i] - '0');
return flag * res;
}
int evalRPN(vector<string>& tokens)
{
if (tokens.size() == 0)
return 0;
stack<int> si;
int left, right;
for(int i = 0; i < tokens.size(); i++)
{
if (tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/")
si.push(str2int(tokens[i]));
else
{
right = si.top();
si.pop();
left = si.top();
si.pop();
if (tokens[i] == "+")
si.push(left+right);
else if (tokens[i] == "-")
si.push(left-right);
else if (tokens[i] == "*")
si.push(left*right);
else if (tokens[i] == "/")
si.push(left/right);
}
}
return si.top();
}
};