-
Notifications
You must be signed in to change notification settings - Fork 0
/
BasicCalculatorII4.py
39 lines (38 loc) · 1.04 KB
/
BasicCalculatorII4.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
class Solution:
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
i = 0
pre = 0
result = 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 == '+':
result += pre
pre = num
elif sign == '-':
result += pre
pre = -num
elif sign == '*':
pre *= num
elif sign == '/':
if pre > 0:
pre = pre // num
else:
pre = -((-pre) // num)
elif s[i] != ' ':
sign = s[i]
i += 1
return result + pre
if __name__ == '__main__':
s = raw_input()
solution = Solution()
print(solution.calculate(s))