class Solution:
def calculate(self, s: str) -> int:
s = s.replace(' ', '')
s = list(s)
stack = []
i = 0
while i < len(s):
temp = s[i]
if temp in '+-*/':
i += 1
num = 0
while i < len(s) and s[i].isdigit():
num = num * 10 + int(s[i])
i += 1
if temp == '-':
num = -num
elif temp in '*/':
num1 = stack.pop()
if temp == '*':
num = num1 * num
else:
if num1 < 0:
num = -((-num1) // num)
else:
num = num1//num
stack.append(num)
return sum(map(int, stack))
计算器 python 栈
最新推荐文章于 2021-09-27 10:02:45 发布