-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
37 lines (30 loc) · 953 Bytes
/
main.py
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
28
29
30
31
32
33
34
35
36
37
class Solution:
def calculate(self, s: str) -> int:
p = 0
def parseNumber() -> int:
nonlocal p
result = 0
while p < len(s) and s[p].isdigit():
result = result * 10 + int(s[p])
p += 1
p -= 1
return result
def parseExpression() -> int:
nonlocal p
result = 0
sign = 1
while p < len(s) and s[p] != ")":
if s[p] == "+":
sign = 1
elif s[p] == "-":
sign = -1
elif s[p] == "(":
p += 1
result += parseExpression() * sign
elif s[p] == ")":
return result
elif s[p].isdigit():
result += parseNumber() * sign
p += 1
return result
return parseExpression()