def calculate(self, s: str) -> int:
stack,base = [],'0123456789'
i,n = 0,len(s)
while i < n:
if s[i] == " ":
i += 1
continue
c = s[i] # 保存操作符
if c in '+-*/': #找到数字的位置
i += 1
while i < n and s[i] == " ":
i += 1
num = 0
while i < n and s[i] in base: #如果是连续数字,需要更新栈顶数据
num = num * 10 + int(s[i])
i += 1
if c == '-': # 根据之前保存的操作符对应计算
num = -num
elif c == '*':
num = stack.pop()*num
elif c == '/':
tmp = stack.pop()
num = int(operator.truediv(tmp, num)) # 等同于下面代码 改变python原有除法取整
# if (tmp > 0 and num < 0):
# num = -(tmp // (-num))
# elif (tmp < 0 and num > 0):
# num = -((-tmp) // num)
# elif (tmp<0 and num<0):
# num = (-tmp) // (-num)
# else:
# num = tmp//num
stack.append(num)
return sum(stack)
网友评论