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
public class Solution {
public int evalRPN(String[] tokens) {
if(tokens.length == 0)
return 0;
Stack<String> stack = new Stack<String>();
int count = 0;
while(count < tokens.length) {
stack.push(tokens[count]);
if(isOperator(stack.peek())) {
String operator = stack.pop();
String paramB = stack.pop();
String paramA = stack.pop();
int result = calculate(operator,
Integer.parseInt(paramA),
Integer.parseInt(paramB));
stack.push(String.valueOf(result));
}
count++;
}
return Integer.parseInt(stack.pop());
}
public boolean isOperator(String str) {
if(str.equals("+") || str.equals("-")
|| str.equals("*") || str.equals("/"))
return true;
return false;
}
public int calculate(String type, int paramA, int paramB) {
int result = 0;
switch (type) {
case "+":
result = paramA + paramB;
break;
case "-":
result = paramA - paramB;
break;
case "*":
result = paramA * paramB;
break;
case "/":
result = paramA / paramB;
break;
}
return result;
}
}