LeetCode 150. Evaluate Reverse Polish Notation

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
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> stk;
int ans = 0;
for (string& token : tokens) {
if (token == "+" || token == "-" || token == "*" || token == "/") {
int num2 = stk.top(); stk.pop();
int num1 = stk.top(); stk.pop();
switch (token[0]) {
case '+':
stk.push(num1 + num2);
break;
case '-':
stk.push(num1 - num2);
break;
case '*':
stk.push(num1 * num2);
break;
case '/':
stk.push(num1 / num2);
break;
}
} else {
stk.push(atoi(token.c_str()));
}
}
return stk.top();
}
};