-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasic Calculator II
More file actions
28 lines (25 loc) · 807 Bytes
/
Basic Calculator II
File metadata and controls
28 lines (25 loc) · 807 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
class Solution:
def calculate(self, s: str) -> int:
stack = []
op = {"+","-","*", "/"}
sign = "+"
s= s.replace(" " , "")
ind = 0
while ind < len(s):
num = ""
while ind < len(s) and s[ind] not in op:
num += s[ind]
ind += 1
if sign == "+":
stack.append(int(num))
elif sign == "-":
stack.append(-int(num))
elif sign == "*":
ans = stack.pop()
stack.append(ans*int(num))
elif sign == "/":
ans = stack.pop()
stack.append(int(ans / int(num)))
if ind < len(s) : sign = s[ind]
ind += 1
return sum(stack)