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
import java.util.*;
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> intStack = new Stack<Integer>();
for(int i = 0; i < tokens.length; i++){
if(tokens[i].equals("+") || tokens[i].equals("-") ||
tokens[i].equals("*") || tokens[i].equals("/")){
int b = intStack.pop();
int a = intStack.pop();
intStack.push(Cal(tokens[i], a, b));
}
else{
intStack.push(Integer.parseInt(tokens[i]));
}
}
return intStack.pop();
}
public int Cal(String s, int a, int b){
if(s.equals("+")){
return a+b;
}
else if(s.equals("-")){
return a-b;
}
else if(s.equals("*")){
return a*b;
}
else
return a/b;
}
}