https://leetcode.com/problems/evaluate-reverse-polish-notation/
这题目简单。但是有个知识点要注意。
参考http://www.cnblogs.com/zuoyuan/p/3760530.html
这里需要注意的一点是python中的’/’除法和c语言不太一样。在python中,(-1)/2=-1,而在c语言中,(-1)/2=0。也就是c语言中,除法是向零取整,即舍弃小数点后的数。而在python中,是向下取整的,相当于math.floor()。而这道题的oj是默认的c语言中的语法,所以需要在遇到’/’的时候注意一下。
class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
help = ['+', '-', '*', '/']
stack = []
for s in tokens:
if s not in help:
stack.append(int(s))
else:
a2 = stack.pop()
a1 = stack.pop()
if s == '+': stack.append(a1 + a2)
if s == '-': stack.append(a1 - a2)
if s == '*': stack.append(a1*a2)
if s == '/':
if a1 * a2 < 0:
stack.append(-(-a1/a2))
else:
stack.append(a1/a2)
return stack[-1]