边工作边刷题:70天一遍leetcode: day 9-1
Evaluate Reverse Polish Notation
这里需要注意的一点是python中的'/'除法和c语言不太一样。在python中,(-1)/2=-1,而在c语言中,(-1)/2=0。也就是c语言中,除法是向零取整,即舍弃小数点后的数。而在python中,是向下取整的。而这道题的oj是默认的c语言中的语法,所以需要在遇到'/'的时候注意一下。
class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
def isOp(word):
if word=="+" or word=="-" or word=="*" or word=="/":
return True
return False
def compute(num1, num2, op):
if op=="+":
return num1+num2
if op=="-":
return num1-num2
if op=="*":
return num1*num2
if op=="/":
if num1*num2 < 0:
return -(-num1/num2)
else:
return num1/num2
stk = []
for t in tokens:
if isOp(t):
num2 = stk.pop()
num1 = stk.pop()
stk.append(compute(num1, num2, t))
else:
# print t
stk.append(int(t))
return stk[-1]