-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path227_basicCalculatorII.py
52 lines (33 loc) · 1.33 KB
/
227_basicCalculatorII.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# 227. Basic Calculator II
from collections import deque
class Solution:
def calculate(self, s: str) -> int:
currNum = 0
operation = '+'
l = len(s)
if l==0:
return 0
stack = deque([])
for i in range(l):
currChar = s[i]
if currChar.isdigit():
currNum = currNum*10 + int(currChar)
if (not currChar.isdigit() and currChar!=" ") or (i==l-1):
if operation=='-':
stack.appendleft(-currNum)
elif operation=='+':
stack.appendleft(currNum)
elif operation=='*':
num = stack.popleft()
currNum = num*currNum
stack.appendleft(currNum)
elif operation=='/':
num = stack.popleft()
currNum = int(num/currNum)
stack.appendleft(currNum)
operation = currChar
currNum = 0
result = 0
while stack:
result+=stack.popleft()
return result