题目227:基本计算机(I)
给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。整数除法仅保留整数部分。
解答:
class Solution:
def calculate(self, s: str) -> int:
stack=[]
pre_op='+'
num=0
for i,each in enumerate(s):
if each.isdigit():
num=10*num+int(each)
if i==len(s)-1 or each in '+-*/' :
if pre_op=='+':
stack.append(num)
elif pre_op=='-':
stack.append(-num)
elif pre_op=='*':
stack.append(stack.pop()*num)
elif pre_op=='/':
top=stack.pop()
if top<0:
stack.append(int(top/num))
else:
stack.append(top//num)
num=0
pre_op=each
return sum(stack)
题目224:基本计算器(I)
给你一个字符串表达式 s ,请你实现一个基本计算器来计算并返回它的值。
解答:
class Solution:
def calculate(self, s: str) -> int:
res, num, sign = 0, 0, 1
stack = []
for c in s:
if c.isdigit():
num = 10 * num + int(c)
elif c == "+" or c == "-":
res += sign * num
num = 0
sign = 1 if c == "+" else -1
elif c == "(":
stack.append(res)
stack.append(sign)
res = 0
sign = 1
elif c == ")":
res += sign * num
num = 0
res *= stack.pop()
res += stack.pop()
res += sign * num
return res