Evaluate Reverse Polish Notation | LeetCode | Java
Tanuja V
Posted on June 6, 2024
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();
}
}
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
💖 💪 🙅 🚩
Tanuja V
Posted on June 6, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.