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