-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasicCalculatorII.py
More file actions
38 lines (36 loc) · 1.05 KB
/
BasicCalculatorII.py
File metadata and controls
38 lines (36 loc) · 1.05 KB
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
class Solution:
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
stack = []
i = 0
sign = '+'
while i < len(s):
if s[i].isdigit():
j = i + 1
while j < len(s) and s[j].isdigit():
j += 1
num = int(s[i : j])
i = j - 1
if sign == '+':
stack.append(num)
elif sign == '-':
stack.append(-num)
elif sign == '*':
stack[-1] = stack[-1] * num
elif sign == '/':
if stack[-1] > 0:
stack[-1] = stack[-1] // num
else:
stack[-1] = -((-stack[-1]) // num)
elif s[i] != ' ':
sign = s[i]
print(stack)
i += 1
return sum(stack)
if __name__ == '__main__':
s = raw_input()
solution = Solution()
print(solution.calculate(s))