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

Discuss

class Solution {
public:
    int evalRPN(vector<string> &tokens) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        
        int len = tokens.size();
        stack<int> s;
        for(int i=0;i<len;i++)
        {
            if(tokens[i]=="+"||tokens[i]=="-"||tokens[i]=="*"||tokens[i]=="/")
            {
                int op2= s.top();s.pop();
                int op1= s.top();s.pop();
                char optor =tokens[i][0];
                if(optor == '+')s.push( op1 + op2);
                 else if(optor == '-')s.push( op1 - op2);
                 else if(optor == '*') s.push( op1 * op2);
                  else s.push(op1 / op2);
            }
            else
            s.push(stoi(tokens[i]));
        }
        return s.top();
    }
        
};


你可能感兴趣的:(Evaluate Reverse Polish Notation)