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