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> result; vector<string>::const_iterator it = tokens.begin(); int num1,num2,temp; while (it != tokens.end()) { if( (*it != "*") && (*it != "+") && (*it != "-") && (*it != "/") ) { result.push(atoi((*it).c_str())); it++; } else { num2 = result.top(); result.pop(); num1 = result.top(); result.pop(); if (*it == "+") { temp = num1 + num2; result.push(temp); } else if (*it == "-") { temp = num1 - num2; result.push(temp); } else if (*it == "*") { temp = num1 * num2; result.push(temp); } else if (*it == "/") { temp = num1 / num2; result.push(temp); } it++; } } return result.top(); } };