프로그래밍/LeetCode
[LeetCode][Python3] 227. Basic Calculator II
snoopybox
2019. 4. 9. 03:10
Problem :
https://leetcode.com/problems/basic-calculator-ii/
My Solution :
class Solution:
def calculate(self, s: str) -> int:
s = s.replace(' ', '') + '+'
total = before = 0
sign = '+'
start = 0
for i in range(len(s)):
if s[i] in ('+', '-', '*', '/'):
num = int(s[start:i])
if sign == '+':
total += before
before = num
elif sign == '-':
total += before
before = -num
elif sign == '*':
before *= num
else:
before = int(before/num)
start = i+1
sign = s[i]
return total + before