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) { int a, b; stack<int> s; for(int i = 0; i < tokens.size(); i ++) { if(isdigit(tokens[i][0]) || tokens[i].length() > 1) { s.push(atoi(tokens[i].c_str())); continue; } a = s.top();s.pop(); b = s.top();s.pop(); switch(tokens[i][0]) { case '+': s.push(b + a); break; case '-': s.push(b - a); break; case '*': s.push(b * a); break; case '/': s.push(b / a); break; } } return s.top(); } };