150. Evaluate Reverse Polish Notation
Evaluate Reverse Polish Notation
Solution
public class Solution {
public int evalRPN(String[] tokens) {
Stack<String> stack = new Stack<>();
for(String s:tokens) {
switch (s) {
case "+":
case "-":
case "*":
case "/":
int a = Integer.valueOf(stack.pop());
int b = Integer.valueOf(stack.pop());
int c = a+b;
if (s.equals("-")) {
c = b - a;
} else if (s.equals("*")) {
c = a*b;
} else if (s.equals("/")) {
c = b / a;
}
stack.push(String.valueOf(c));
break;
default:
stack.push(s);
break;
}
}
return Integer.valueOf(stack.pop());
}
}Last updated