Evaluate Reverse Polish Notation

来源:互联网 发布:淘宝如何下架宝贝 编辑:程序博客网 时间:2024/05/19 14:01

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


Solution:

class Solution {public:    int str2num(string str)    {        int num;        stringstream ss;        ss << str;        ss >> num;        return num;    }    int evalRPN(vector<string>& tokens) {        stack<int> s;        for(int i = 0; i < tokens.size(); ++i)        {            int x, y;            if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/")            {                y = s.top();                s.pop();                x = s.top();                s.pop();                if(tokens[i] == "+") s.push(x + y);                else if(tokens[i] == "-") s.push(x - y);                else if(tokens[i] == "*") s.push(x * y);                else s.push(x / y);            }            else s.push(str2num(tokens[i]));        }        return s.top();    }};


0 0
原创粉丝点击