首页 > 代码库 > Evaluate Reverse Polish Notation

Evaluate Reverse Polish Notation

方法:别弄反数字之间的位置关系就可以了

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<string> ss;
        int result;
        
        for(int i=0; i<tokens.size(); ++i)
        {
            if(isOperator(tokens[i]))
            {
                int num2 = stoi(ss.top());
                ss.pop();
                int num1 = stoi(ss.top());
                ss.pop();
                
                if(tokens[i] == "+")
                    num1 += num2;
                else if(tokens[i] == "-")
                    num1 -= num2;
                else if(tokens[i] == "*")
                    num1 *= num2;
                else
                    num1 /= num2;
                
                ss.push(to_string(num1));
            }
            else
                ss.push(tokens[i]);
        }
        
        return stoi(ss.top());
    }
    
    bool isOperator(string s)
    {
        return s.size() == 1 && string("+-*/").find(s) != string::npos;
    }
};

 

Evaluate Reverse Polish Notation