evaluate-reverse-polist-notation leetcode C++

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

C++

class Solution {
public:
    int evalRPN(vector<string> &tokens){
        int len = tokens.size();
        stack<int> S;
        for (int i = 0; i< len; i++){
            if ("+" == tokens[i] || "-" == tokens[i] || tokens[i] == "*" || tokens[i] == "/"){
                int arg2 = S.top(); S.pop();
                int arg1 = S.top(); S.pop();
                S.push(runOperator(arg1,arg2,tokens[i][0]));
            }else
                S.push(stoi(tokens[i]));
        }
        return S.top();
    }
    int runOperator(int arg1,int arg2,char optor){
        if('+' == optor) return arg1 + arg2;
        else if('-' == optor) return arg1 - arg2;
        else if('*' == optor) return arg1 * arg2;
        else return arg1 / arg2;
    }
};

 

posted @ 2018-09-21 11:34  vercont  阅读(132)  评论(0编辑  收藏  举报