-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic-calculator-iii.py
More file actions
30 lines (30 loc) · 936 Bytes
/
basic-calculator-iii.py
File metadata and controls
30 lines (30 loc) · 936 Bytes
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
class Solution:
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
num, stack, sign = 0, [], "+"
s += " "
i = 0
while i < len(s):
if s[i].isdigit():
num = num * 10 + int(s[i])
elif s[i] == "(":
num, skip = self.calculate(s[i + 1 :])
i += skip
elif s[i] in "+-*/)" or i == len(s) - 1:
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))
if s[i] == ")":
return sum(stack), i + 1
num = 0
sign = s[i]
i += 1
return sum(stack)