算术表达式的计算
题意:
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
法一:非递归
- 建立一个栈存储数字
- 遇到符号,数字栈的前两个弹出,注意顺序!后弹出的+-*/先弹出的
- 计算结果压回栈中
- 计算结束后,s.peek()即为所求结果。
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String s : tokens) {
switch (s) {
case "+":
stack.push(stack.pop() + stack.pop());
break;
case "-":
int temp = stack.pop();
stack.push(stack.pop() - temp);
break;
case "*":
stack.push(stack.pop() * stack.pop());
break;
case "/":
temp = stack.pop();
stack.push(stack.pop() / temp);
break;
default:
stack.push(Integer.parseInt(s));
break;
}
}
return stack.peek();
}
法二:递归
- 从后往前检查数组,遍历到符号时,不断循环找到两个数;遍历到数时,parseInt转成Integer。如果遇到新符号,先计算新符号。
public class Solution {
int index;
public int evalRPN(String[] tokens) {
index = tokens.length - 1;
return recurse(tokens);
}
private int recurse(String[] tokens) {
String word = tokens[index--];
int a, b;
switch (word) {
case "+":
b = recurse(tokens);
a = recurse(tokens);
return a + b;
case "-":
b = recurse(tokens);
a = recurse(tokens);
return a - b;
case "*":
b = recurse(tokens);
a = recurse(tokens);
return a * b;
case "/":
b = recurse(tokens);
a = recurse(tokens);
return a / b;
default:
return Integer.parseInt(word);
}
}
}