leetcode 150. Evaluate Reverse Polish Notation

来源:互联网 发布:网络言论自由的事例 编辑:程序博客网 时间:2024/06/14 10:35

150. 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
计算后缀表达式!用STACK

class Solution {public:    int evalRPN(vector<string>& tokens)     {        stack<int> shuzi;        for (int i = 0; i < tokens.size(); i++)        {            if(tokens[i] == "+")             {                int a = shuzi.top();                 shuzi.pop();                int b = shuzi.top();                shuzi.top() = a + b;             }             else if(tokens[i] == "-")             {                int a = shuzi.top();                 shuzi.pop();                int b = shuzi.top();                shuzi.top() = b - a;             }            else if(tokens[i] == "*")             {                int a = shuzi.top();                 shuzi.pop();                int b = shuzi.top();                shuzi.top() = a * b;             }            else if(tokens[i] == "/")             {                int a = shuzi.top();                 shuzi.pop();                int b = shuzi.top();                shuzi.top() = b / a;             }            else                shuzi.push( atoi(tokens[i].c_str()) );        }        return shuzi.top();    }};


原创粉丝点击