-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path227. Basic-Calculator-II
65 lines (52 loc) · 1.85 KB
/
227. Basic-Calculator-II
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
53
54
55
56
57
58
59
60
61
62
class Solution:
def calculate(self, s: str) -> int:
stack = []
currentNumber = 0
sign = 1
i = 0
while i < len(s):
if s[i] in ['+','-']:
stack.extend([sign, currentNumber])
currentNumber = 0
sign = 1 if s[i] == '+' else -1
elif s[i] in ['*','/']:
j = i + 1
nextNumber = 0
while j < len(s) and (s[j].isdigit() or s[j] == ' '):
if s[j].isdigit():
nextNumber = nextNumber * 10 + int(s[j])
j += 1
if s[i] == '*':
currentNumber *= nextNumber
else:
currentNumber = math.floor(currentNumber / nextNumber)
i = j - 1
elif s[i].isdigit():
currentNumber = currentNumber * 10 + int(s[i])
if i == len(s) - 1:
stack.extend([sign, currentNumber])
i += 1
res = 0
for i in range(0,len(stack),2):
res += stack[i] * stack[i+1]
return res
class Solution:
def calculate(self, s: str) -> int:
value, n = 0, len(s)
sign = '+'
stack = []
for i, char in enumerate(s):
if char.isdigit():
value = value * 10 + int(char)
if i == n - 1 or char in '+-*/':
if sign == '+':
stack.append(value)
elif sign == '-':
stack.append(-value)
elif sign == '*':
stack.append(stack.pop() * value)
elif sign == '/':
stack.append(int(stack.pop() / value))
sign = char
value = 0
return sum(stack)