Skip to content

top145-#150 #8

Description

@LionCoder4ever
  • use stack instore the token, once get a operation, pop 2 num, eval the value and push to stack
class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> stack;
        int n = tokens.size();
        for(int i=0;i<n;i++) {
            string s = tokens[i];
            bool isOp = s == "+" || s == "-" || s == "*" || s == "/";
            if (isOp) {
                int a = stack.top();
                stack.pop();
                int b =  stack.top();
                stack.pop();
                if (s == "+")  {
                    stack.push(a + b);
                } else if(s == "-") {
                    stack.push(b - a);
                } else if(s == "*"){
                    stack.push(a * b);
                } else {
                    stack.push(b / a);
                }
            } else {
                stack.push(stoi(s));
            }
        }
        return stack.top();
    }
};

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions