题目描述
根据逆波兰表示法,求表达式的值。
有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。
算法思想
遍历字符串,若为数字就入栈,若为运算符,则将数字出栈进行运算
Java代码
public int evalRPN(String[] tokens) {
Stack<Integer> s = new Stack<>();
int a , b;
for(String str : tokens){
if(str.equals("+")){
s.push(s.pop() + s.pop());
}else if(str.equals("-")){
b = s.pop();
a = s.pop();
s.push(a - b);
}else if(str.equals("*")){
s.push(s.pop() * s.pop());
}else if(str.equals("/")){
b = s.pop();
a = s.pop();
s.push(a / b);
}else{
try{
int num = Integer.parseInt(str);
s.push(num);
}catch(NumberFormatException e){
e.printStackTrace();
}
}
}
return s.pop();
}