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