问题:
用反波兰式表示算术表达式的值。
有效运算符是+,-,*,/。每个操作数可以是一个整数或另一个表达式。
一些例子:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
答案:
public class Solution {
public int evalRPN(String[] tokens) {
Stack<String> stack = new Stack<String>();
for(int i=0;i<tokens.length;i++){
if(tokens[i].equals("+")){
int n = Integer.parseInt(stack.pop());
int m = Integer.parseInt(stack.pop());
stack.push(String.valueOf(n+m));
}else if(tokens[i].equals("-")){
int n = Integer.parseInt(stack.pop());
int m = Integer.parseInt(stack.pop());
stack.push(String.valueOf(m-n));
}else if(tokens[i].equals("*")){
int n = Integer.parseInt(stack.pop());
int m = Integer.parseInt(stack.pop());
stack.push(String.valueOf(n*m));
}else if(tokens[i].equals("/")){
int n = Integer.parseInt(stack.pop());
int m = Integer.parseInt(stack.pop());
int re;
if(m == 0){
re = 0;
}else{
re = m/n;
}
stack.push(String.valueOf(re));
}else {
stack.push(tokens[i]);
}
}
return Integer.parseInt(stack.pop());
}
}