Skip to content

top145-#150 #8

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Open
LionCoder4ever opened this issue Oct 4, 2021 · 0 comments
Open

top145-#150 #8

LionCoder4ever opened this issue Oct 4, 2021 · 0 comments

Comments

@LionCoder4ever
Copy link
Owner

  • 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();
    }
};
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant