力扣 224. 基本计算器

栈处理op

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
def cal(s):
op = [1]
sign, res = 1, 0
i, s_len = 0, len(s)
while i < s_len:
if s[i] == " ":
i += 1
elif s[i] == "+":
sign = op[-1]
i += 1
elif s[i] == "-":
sign = -op[-1]
i += 1
elif s[i] == "(":
op.append(sign)
i += 1
elif s[i] == ")":
op.pop()
i += 1
else:
num = 0
while i < s_len and s[i].isdigit():
num = num * 10 + ord(s[i]) - ord("0")
i += 1
res += sign * num

return res
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2022 eightyninth
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信