Evaluate Reverse Polish Notation
Source
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
Java
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<Integer>();
for(String s: tokens){
if(s.equals("+")){
stack.push(stack.pop() + stack.pop());
}
else if(s.equals("-")){
int a = stack.pop();
int b = stack.pop();
stack.push(b-a);
}
else if(s.equals("*")){
stack.push(stack.pop() * stack.pop());
}
else if(s.equals("/")){
int a = stack.pop();
int b = stack.pop();
stack.push(b/a);
}
else{
stack.push(Integer.parseInt(s));
}
}
return stack.pop();
}
}
public class Solution {
public int evalRPN(String[] tokens) {
int result = Integer.MIN_VALUE;
Stack<Integer> stack = new Stack<Integer>();
for(int i=0; i< tokens.length; i++){
if(tokens[i].equals("-") || tokens[i].equals("+") || tokens[i].equals("*") || tokens[i].equals("/")){
try{
switch (tokens[i].charAt(0)){
case '+' :
result = stack.pop() + stack.pop();
break;
case '-' :
result = stack.pop();
result = stack.pop() - result;
break;
case '*' :
result = stack.pop() * stack.pop();
break;
case '/' :
result = stack.pop();
if (result == 0)
return Integer.MIN_VALUE;
result = stack.pop() / result;
}
stack.push(result);
}catch(EmptyStackException e){
return Integer.MIN_VALUE;
}
continue;
}
try{
stack.push(Integer.parseInt(tokens[i]));
}catch(NumberFormatException e){
return Integer.MIN_VALUE;
}
}
if (!stack.isEmpty())
result = stack.pop();
return stack.isEmpty() ? result : Integer.MIN_VALUE;
}
}