LeetCode题解——Evaluate Reverse Polish Notation

来源:互联网 发布:爱知学院大学 编辑:程序博客网 时间:2024/06/09 14:51

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) {        stack<int> s;        int v1,v2;        for(auto c:tokens){            if(c=="*"){                v1 = s.top(); s.pop();                v2 = s.top(); s.pop();                s.push(v1*v2);            }            else if(c=="/"){                v1 = s.top(); s.pop();                v2 = s.top(); s.pop();                s.push(int(v2/v1));            }            else if(c=="+"){                v1 = s.top(); s.pop();                v2 = s.top(); s.pop();                s.push(v1+v2);            }            else if(c=="-"){                v1 = s.top(); s.pop();                v2 = s.top(); s.pop();                s.push(v2-v1);            }            else s.push(stoi(c));        }        return s.top();    }};


0 0