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

计算逆波兰表达式

 1 class Solution {
 2 public:
 3     int calc(int & l,int & r,const string & oper){
 4         if(oper=="+") return l+r;
 5         if(oper=="-") return l-r;
 6         if(oper=="*") return l*r;
 7         if(oper=="/") return l/r;
 8         throw "wrong oper";
 9     }
10 
11     int eval(vector<string>::const_reverse_iterator & ita){
12         const string & oper = *ita;
13         if(oper == "+" || oper == "-" || oper == "*" || oper == "/"){ //运算符号
14             ++ita;
15             int r = eval(ita);
16             int l= eval(ita);
17             return calc(l,r,oper);
18         }else{
19             ++ita;
20             return atoi(oper.c_str());
21         }
22     }
23 
24     int evalRPN(vector<string> &tokens) {
25         vector<string>::const_reverse_iterator  ita = tokens.rbegin();
26         return eval(ita);
27     }
28 };

 


 

posted @ 2014-10-22 14:35  Madao_  阅读(118)  评论(0)    收藏  举报