Basic Calculator LeetCode solution in Python

1
# Runtime: 137 ms (Top 57.95%) | Memory: 15.5 MB (Top 50.78%)
2

3

4
class Solution:
5
def calculate(self, s: str) -> int:
6
curr, output, sign, stack = 0, 0, 1, []
7

8
for ch in s:
9
if ch.isdigit():
10
curr = curr * 10 + int(ch)
11

12
elif ch == "+":
13
output += sign * curr
14
sign = 1
15
curr = 0
16

17
elif ch == "-":
18
output += sign * curr
19
sign = -1
20
curr = 0
21

22
elif ch == "(":
23
# push the result and then the sign
24
stack.append(output)
25
stack.append(sign)
26
sign = 1
27
output = 0
28

29
elif ch == ")":
30
output += sign * curr
31
output *= stack.pop()
32
output += stack.pop()
33
curr = 0
34
return output + sign * curr

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0