[leetcode]evaluate-reverse-polish-notation

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/coolwriter/article/details/79960734

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) {
        if(tokens.size() == 0)
            return 0;
        stack<int> st;
        for(int i = 0; i < tokens.size(); ++i)
        {
            string s = tokens[i];
            if(s == "+" || s == "-" || s == "*" || s == "/")
            {
                if(st.size() < 2)
                    return 0;
                int num2 = st.top(); st.pop();
                int num1 = st.top(); st.pop();
                int result = 0;

                if(s == "+")
                    result = num1 + num2;
                else if(s == "-")
                    result = num1 - num2;
                else if(s == "*")
                    result = num1 * num2;
                else if(s == "/")
                    result = num1 / num2;
                st.push(result);
            }
            else
            {
                st.push(atoi(s.c_str()));
            }  
        }
        return st.top();
    }
};
阅读更多

没有更多推荐了,返回首页