Skip to content

Commit a9009c2

Browse files
committed
逆波兰表达式求值
1 parent 25ee7f7 commit a9009c2

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
# @param {string[]} tokens The Reverse Polish Notation
5+
# @return {int} the value
6+
def evalRPN(self, tokens):
7+
# Write your code here
8+
ret = []
9+
for item in tokens:
10+
if self.isOperator(item):
11+
right_val = ret.pop()
12+
left_val = ret.pop()
13+
if item == '*':
14+
ret.append(left_val * right_val)
15+
elif item == '/':
16+
# Python对于正负数相除有问题,需要单独处理
17+
hack = ((left_val > 0) and (right_val < 0)) or ((left_val < 0) and (right_val > 0))
18+
div = abs(left_val) / abs(right_val)
19+
if hack:
20+
div = -1 * int(div)
21+
ret.append(div)
22+
elif item == '+':
23+
ret.append(left_val + right_val)
24+
else:
25+
ret.append(left_val - right_val)
26+
else:
27+
ret.append(int(item))
28+
return 0 if not ret else ret[0]
29+
30+
def isOperator(self, item):
31+
return (item == '+') or (item == '-') or (item == '*') or (item == '/')

0 commit comments

Comments
 (0)