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 calc(int & l,int & r,const string & oper){
if(oper=="+") return l+r;
if(oper=="-") return l-r;
if(oper=="*") return l*r;
if(oper=="/") return l/r;
throw "wrong oper";
}
int eval(vector<string>::const_reverse_iterator & ita){
const string & oper = *ita;
if(oper == "+" || oper == "-" || oper == "*" || oper == "/"){ //运算符号
++ita;
int r = eval(ita);
int l= eval(ita);
return calc(l,r,oper);
}else{
++ita;
return atoi(oper.c_str());
}
}
int evalRPN(vector<string> &tokens) {
vector<string>::const_reverse_iterator ita = tokens.rbegin();
return eval(ita);
}
};