-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0227-basic-calculator-ii.py
More file actions
38 lines (34 loc) · 1007 Bytes
/
0227-basic-calculator-ii.py
File metadata and controls
38 lines (34 loc) · 1007 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
31
32
33
34
35
36
37
38
# time complexity: O(n)
# space complexity: O(n)
import math
class Solution:
def calculate(self, s: str) -> int:
num = 0
prevOperation = '+'
s += '+'
stack = []
for c in s:
if c.isdigit():
num = num*10 + int(c)
elif c == ' ':
pass
else:
if prevOperation == '+':
stack.append(num)
elif prevOperation == '-':
stack.append(-num)
elif prevOperation == '*':
operant = stack.pop()
stack.append((operant*num))
elif prevOperation == '/':
operant = stack.pop()
stack.append(math.trunc(operant/num))
num = 0
prevOperation = c
return sum(stack)
s = "3+2*2"
print(Solution().calculate(s))
s = " 3/2 "
print(Solution().calculate(s))
s = " 3+5 / 2 "
print(Solution().calculate(s))