题目描述:
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
思路:
简单的逆波兰表达式,注意leetcode应该是使用的python2.x的编译器,在python2.x下倆符号不同的数字的除法结果是向下保留的,和python3.x以及c是不同的。举个例子:2/-3在c或者python3.x中结果应该是0,但是在python2.x中结果是-1。之前一直没注意到这个问题导致老是WA。
python代码:
class Solution:
def calculate(self,a,b,op):
if op == "+":
return b+a
elif op == "-":
return b-a
elif op == "*":
return b*a
elif op == "/":
if b*a<0:
return -(-b/a)
return b/a
def evalRPN(self,tokens):
ans = []
for i in tokens:
if i in ["+","-","*","/"]:
top = self.calculate(ans.pop(),ans.pop(),i)
ans.append(top)
else:
ans.append(int(i))
return ans.pop()