题解 | #表达式求值#
表达式求值
https://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d
def calculate(s: str) -> int:
def helper(s: list) -> int:
stack = []
num = 0
sign = "+"
while len(s) > 0:
c = s.pop(0)
if c.isdigit():
num = num * 10 + int(c)
if c == "(":
num = helper(s)
if len(s) == 0 or c in "+-*/)":
if sign == "+":
stack.append(num)
elif sign == "-":
stack.append(-num)
elif sign == "*":
stack.append(stack.pop() * num)
elif sign == "/":
stack.append(int(stack.pop() / num)) # 确保整数除法向下取整
num = 0
sign = c
if c == ")":
break
return sum(stack)
# 为了使用pop(0)操作,将字符串转换成列表
return helper(list(s))
# 输入字符串
s = input().replace(" ", "") # 删除空格
# 输出计算结果
print(calculate(s))
