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

class Solution {
public:
    int evalRPN(vector<string> &tokens) {
            int sum;
    string operators="+-*/";
    stack<int>sta;
    for(int i=0;i<tokens.size();i++){
        if(operators.find(tokens[i])==string::npos){
            sta.push(atoi(tokens[i].c_str()));
        }

        else{
            int a=sta.top();
            sta.pop();
            int b=sta.top();
            sta.pop();
            if(tokens[i]=="+"){
                sta.push(a+b);
            }
            if(tokens[i]=="-"){
                sta.push(b-a);
            }
            if(tokens[i]=="*"){
                sta.push(a*b);
            }
            if(tokens[i]=="/"){
                sta.push(b/a);
            }
        }
        

    
    }

    sum=sta.top();
    return sum;
    }
};

 

posted @ 2015-02-01 15:12  mrpod2g  阅读(118)  评论(0编辑  收藏  举报