generated from zeikar/issueage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasic-calculator.py
34 lines (31 loc) · 997 Bytes
/
basic-calculator.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
class Solution:
def calculate(self, s: str) -> int:
num_stack = [0]
op_stack = [1]
num = 0
s = '(' + s + ')'
for i in range(len(s)):
if s[i].isdigit():
num = num * 10 + int(s[i])
elif s[i] == '+':
op = op_stack.pop()
num_stack[-1] += num * op
op_stack.append(1)
num = 0
elif s[i] == '-':
op = op_stack.pop()
num_stack[-1] += num * op
op_stack.append(-1)
num = 0
elif s[i] == '(':
num_stack.append(0)
op_stack.append(1)
elif s[i] == ')':
op = op_stack.pop()
num_stack[-1] += num * op
op = op_stack.pop()
n = num_stack.pop()
num_stack[-1] += n * op
op_stack.append(1)
num = 0
return num_stack[0]