67_Add Binary
Input: a = "11", b = "1"
Output: "100"Input: a = "1010", b = "1011"
Output: "10101"Solution 1: loop from right to left iteratively
def addBinary(a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
m = len(a) - 1
n = len(b) - 1
ret = ''
count = 0
while m >= 0 or n >= 0:
if m < 0:
temp = int(b[n]) + count
elif n < 0:
temp = int(a[m]) + count
else:
temp = int(a[m]) + int(b[n]) + count
if temp >= 2:
ret = str(temp - 2) + ret
count = 1
else:
ret = str(temp) + ret
count = 0
m -= 1
n -= 1
if count == 1:
ret = str(count) + ret
return retSolution 2: recursively
Last updated