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 | class Solution {
private:
bool isOperator(string token) {
return token == "+" || token == "-" || token == "*" || token == "/";
}
int performOp(string op, int x, int y) {
if (op == "+")
return x + y;
if (op == "-")
return x - y;
if (op == "*")
return x * y;
if (op == "/")
return x / y;
std::unreachable();
}
public:
int evalRPN(vector<string> &tokens) {
std::stack<int> stack;
for (string token : tokens) {
if (isOperator(token)) {
int opnd2 = stack.top();
stack.pop();
int opnd1 = stack.top();
stack.pop();
stack.push(performOp(token, opnd1, opnd2));
} else
stack.push(std::stoi(token));
}
int result = stack.top();
return result;
}
};
|