题目:
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) {
stack<int> oped;
for(auto it : tokens) {
//数字,进栈
if(isdigit(it[0]) || it.size() > 1) {
oped.push(atoi(it.c_str()));
}
//出栈两个数,计算后入栈
else {
int oped2 = oped.top();
oped.pop();
int oped1 = oped.top();
oped.pop();
switch (it[0]) {
case '+':
oped.push(oped1+oped2);
break;
case '-':
oped.push(oped1-oped2);
break;
case '*':
oped.push(oped1*oped2);
break;
case '/':
oped.push(oped1/oped2);
break;
}
}
}
return oped.top();
}
};