题目描述
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:
用异常处理,感觉很妙。逆波兰数求结果,如果是数字就一直入栈,碰到了符号将栈中的数字弹出,按照遇到的符号进行计算,再将得到的结果作为下一个需要进行计算的数字压入栈中。一直做这个操作。用异常处理检查数组的这一位是否是数字,捕获到符号之后,用求值函数进行求结果。再将结果压入栈。
栈的结构是先进后出,所以在进行计算的时候,一定要记得将先pop出的数字放到符号后面进行计算。
import java.util.Stack;
public class Solution {
public int evalRPN(String[] tokens) {
if(tokens == null || tokens.length == 0){
return 0;
}
Stack<Integer> stack = new Stack<Integer>();
for(int i = 0;i < tokens.length;i++){
try{
int num = Integer.parseInt(tokens[i]);
stack.push(num);
}catch(Exception e){
int b = stack.pop();
int a = stack.pop();
stack.add(get(a,b,tokens[i]));
}
}
return stack.pop();
}
public int get(int a ,int b, String operation){
switch(operation){
case "+":
return a + b;
case "-":
return a - b;
case "*":
return a * b;
case "/":
return a / b;
default:
return 0;
}
}
}