Evaluate Reverse Polish Notation
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这是一个很简单的题目,解答如下 用多个if即可解决
Algorithm:
-
pop string from the end of the vector
-
if it's number, just return it
-
if it's operation, call function recursively for 2nd operand and 1st
int evalRPN(vector<string> &n) {
string s = n.back(); n.pop_back();
if ( s== "" || s=="/" || s=="+" || s == "-" ){
int r2 = evalRPN(n);
int r1 = evalRPN(n);
if ( s=="") return r1*r2;
if ( s=="/") return r1/r2;
if ( s=="+") return r1+r2;
if ( s=="-") return r1-r2;
}
else
return atoi(s.c_str());
}