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

 

 Code:

 

class Solution {
public:
    bool isOperator(string op){
        return (op=="+"||op=="-"||op=="*"||op=="/");
    }
    
    int calculate(int operand1, int operand2, string op){
        if(op=="+")
            return operand1+operand2;
        else if(op=="-")
            return operand1-operand2;
        else if(op=="*")
            return operand1*operand2;
        else
            return operand1/operand2;
    }
    
    int evalRPN(vector<string> &tokens) {
        if(tokens.empty())
            return 0;
        stack<int> store;
        for(int i=0; i<tokens.size(); i++){
            if(isOperator(tokens[i])){
                int operand2 = store.top();
                store.pop();
                int operand1 = store.top();
                store.pop();
                store.push(calculate(operand1, operand2, tokens[i]));
            }
            else
                store.push(stoi(tokens[i]));
        }
        return store.top();
    }
};

 

posted @ 2013-12-13 04:02  WinsCoder  阅读(156)  评论(0编辑  收藏  举报