DEV Community

Tanuja V
Tanuja V

Posted on • Edited on

2 1

Evaluate Reverse Polish Notation | LeetCode | Java

class Solution {
    public int evalRPN(String[] tokens) {

        Stack<Integer> stack = new Stack<>();

        for(String token : tokens){
            if(token.equals("+")){
                int a = stack.pop();
                int b = stack.pop();
                stack.push(a+b);
            }

            else if(token.equals("-")){
                int a = stack.pop();
                int b = stack.pop();
                stack.push(b-a);
            }

            else if(token.equals("*")){
                int a = stack.pop();
                int b = stack.pop();
                stack.push(a*b);
            }

            else if(token.equals("/")){
                int a = stack.pop();
                int b = stack.pop();
                stack.push(b/a);
            }

            else{
                stack.push(Integer.parseInt(token));
            }
        }

        return stack.pop();
    }
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading :)
Feel free to comment and like the post if you found it helpful
Follow for more 🤝 && Happy Coding 🚀

If you enjoy my content, support me by following me on my other socials:
https://linktr.ee/tanujav7

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (1)

Collapse
 
siy profile image
Sergiy Yevtushenko

Why not use switch(token)?

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay