-
Notifications
You must be signed in to change notification settings - Fork 0
/
Evaluate_Reverse_Polish_Notation.cpp
51 lines (48 loc) · 1.49 KB
/
Evaluate_Reverse_Polish_Notation.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
41
42
43
44
45
46
47
48
49
50
51
// Evaluate the value of an arithmetic expression in Reverse Polish Notation.
// Valid operators are +, -, *, /. Each operand may be an integer or another expression.
// Some examples:
// ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
// ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
class Solution {
public:
int evalRPN(vector<string> &tokens) {
if (tokens.empty())
return 0;
stack<int> store;
for (int i = 0; i < tokens.size(); i++) {
if (tokens[i] == "+") {
int a = store.top();
store.pop();
int b = store.top();
store.pop();
store.push(a+b);
}
else if (tokens[i] == "-") {
int a = store.top();
store.pop();
int b = store.top();
store.pop();
store.push(b-a);
}
else if (tokens[i] == "*") {
int a = store.top();
store.pop();
int b = store.top();
store.pop();
store.push(b*a);
}
else if (tokens[i] == "/") {
int a = store.top();
store.pop();
int b = store.top();
store.pop();
store.push(b/a);
}
else {
store.push(atoi(tokens[i].c_str()));
}
}
if (!store.empty())
return store.top();
}
};