Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
Subscribe to see which companies asked this question
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
result = []
a = list(a)
b = list(b)
a_index = len(a) - 1
b_index = len(b) - 1
c = 0
while True:
if a_index >= 0 and b_index >= 0:
result.insert(0,str((int(a[a_index]) + int(b[b_index]) + c) % 2))
c = (int(a[a_index]) + int(b[b_index]) + c) / 2
a_index -= 1
b_index -= 1
elif a_index >= 0:
result.insert(0,str((int(a[a_index]) + c) % 2))
c = (int(a[a_index]) + c) / 2
a_index -= 1
elif b_index >= 0:
result.insert(0,str((int(b[b_index]) + c) % 2))
c = (int(b[b_index]) + c) / 2
b_index -= 1
else:
if c != 0:
result.insert(0, '1')
c = 0
else:
return ''.join(result)