[LeetCode]227. Basic Calculator II
227. Basic Calculator II
栈
print 3//2 # 1
print -3//2 # -2
class Solution(object):
def calculate(self, s):
if not s:
return "0"
stack, num, sign = [], 0, "+"
for i in range(len(s)):
if s[i].isdigit():
num = num * 10 + ord(s[i]) - ord("0")
if (not s[i].isdigit() and not s[i].isspace()) or i == len(s) - 1:
if sign == "-":
stack.append(-num)
elif sign == "+":
stack.append(num)
elif sign == "*":
stack.append(stack.pop() * num)
else:
tmp = stack.pop()
if tmp // num < 0 and tmp % num != 0:
stack.append(tmp // num + 1)
else:
stack.append(tmp // num)
sign = s[i]
num = 0
return sum(stack)
关注公众号:数据结构与算法那些事儿,每天一篇数据结构与算法

浙公网安备 33010602011771号