Iterative
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
if len(a)>len(b): return self.addBinary(b, a)
a = "0"*(len(b)-len(a)) + a
res = ""
carry = 0
for i in range(len(b)-1, -1, -1):
aa = ord(a[i])-ord('0')
bb = ord(b[i])-ord('0')
carry = aa+bb+carry
res = str(carry%2)+res
carry = carry/2
if carry: res = "1" + res
return res
Recursion
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
if len(a)==0: return b
if len(b)==0: return a
if a[-1]=="1" and b[-1]=="1":
return self.addBinary(self.addBinary(a[:-1], b[:-1]), "1")+"0"
elif a[-1]=="0" and b[-1]=="0":
return self.addBinary(a[:-1], b[:-1])+"0"
else:
return self.addBinary(a[:-1], b[:-1])+"1"