Nameless Site

But one day, you will stand before its decrepit gate,without really knowing why.

0%

后缀表达式求值

来源Leetcode第150题逆波兰表达式求值

根据逆波兰表示法,求表达式的值。

有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。

说明:

整数除法只保留整数部分。
给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。
示例 1:

输入: [“2”, “1”, “+”, “3”, ““]
输出: 9
解释: ((2 + 1)
3) = 9

老题目了,操作数压栈,运算符2个操作数出栈,运算后在压栈.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String s : tokens) {
if (s.equals("+")) {
stack.push(stack.pop() + stack.pop());
} else if (s.equals("-")) {
stack.push(-stack.pop() + stack.pop());
} else if (s.equals("*")) {
stack.push(stack.pop() * stack.pop());
} else if (s.equals("/")) {
int num1 = stack.pop();
stack.push(stack.pop() / num1);
} else {
stack.push(Integer.parseInt(s));
}
}
return stack.pop();
}