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
Difficulty: Medium
Solution: Use stack to implement. Two useful fuction: Integer.valueOf, String.valueOf.
public class Solution {
public int evalRPN(String[] tokens) {
String oper = "+-*/";
Stack<String> sta = new Stack<String>();
for(String temp : tokens){
if(!oper.contains(temp)){
sta.push(temp);
}
else{
int num1 = Integer.valueOf(sta.pop());
int num2 = Integer.valueOf(sta.pop());
if(temp.equals("+")){
sta.push(String.valueOf(num2 + num1));
}
if(temp.equals("-")){
sta.push(String.valueOf(num2 - num1));
}
if(temp.equals("*")){
sta.push(String.valueOf(num2 * num1));
}
if(temp.equals("/")){
sta.push(String.valueOf(num2 / num1));
}
}
}
return Integer.valueOf(sta.pop());
}
}