问题描述
思路
有运算符,才append到stack中
是数字的话,等待进位
如果不在s
末尾加入+0
,会导致最后一个运算符后的数字丢失
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
if not s or len(s) == 0:
return 0
s=s+"+0"
num = 0
opt = "+"
stack = []
for i in s:
if i.isdigit():
num = num*10 + int(i)
elif not i.isdigit() and not i.isspace():
if opt == "+":
stack.append(num)
elif opt == "-":
stack.append(-num)
elif opt == "*":
stack.append(stack.pop()*num)
elif opt == "/":
n =stack.pop()
if n<0:
tmp = abs(n)//num
stack.append(-tmp)
else:
stack.append(n//num)
opt = i
num = 0
return int(sum(stack))
网友评论