#leetcode67 add binary
def addBinary(a,b):
length_dif = len(a) - len(b)#find length difference
if length_dif < 0:
a = '0'*(-length_dif )+ a#make two strings' length equal
if length_dif >= 0:
b = '0'*length_dif + b
l = len(a)-1
carry = 0
res = ''
while l >=0:
s = int(a[l]) + int(b[l]) + carry #If I assign a virable to the sum, the function will work.
if s == 2:
res = '0' + res
if s == 3:
res = '1' + res
if s < 2:
res = str(s) + res
l -= 1
if carry:
return str(carry) + res
else:
return res
#from line 12, if I do not assign a viable, just use the expression, the result will be totally different.
#could you tell me what's wrong with the second version ?
def addBinary(a,b):
length_dif = len(a) - len(b)#find length difference
if length_dif < 0:
a = '0'*(-length_dif )+ a#make two strings' length equal
if length_dif >= 0:
b = '0'*length_dif + b
l = len(a)-1
carry = 0
res = ''
while l >=0:
if int(a[l]) + int(b[l]) + carry == 2:
res = '0' + res
if int(a[l]) + int(b[l]) + carry == 3:
res = '1' + res
if int(a[l]) + int(b[l]) + carry < 2:
res = str( int(a[l]) + int(b[l]) + carry) + res
l -= 1
if carry:
return str(carry) + res
else:
return res