150. 逆波兰表达式求值
为保证权益,题目请参考 150. 逆波兰表达式求值(From LeetCode).
解决方案1
Python
python
# 150. 逆波兰表达式求值
# https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/
from typing import List
import math
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
st = []
for token in tokens:
if token == "+":
r = st.pop()
l = st.pop()
t = l + r
st.append(t)
elif token == "-":
r = st.pop()
l = st.pop()
t = l - r
st.append(t)
elif token == "*":
r = st.pop()
l = st.pop()
t = r * l
st.append(t)
elif token == "/":
r = st.pop()
l = st.pop()
t = l / r
if t > 0:
t = math.floor(t)
else:
t = math.ceil(t)
st.append(t)
else:
st.append(int(token))
return st[0]
if __name__ == "__main__":
solution = Solution()
print(
solution.evalRPN(
["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
)
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47