Link to Github

**Brute force method**1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | def add_binary_nums(x, y): print((len(x))) print((len(x))) max_len = max(len(x), len(y)) print("max_len {}".format(max_len)) print() #Fill it with zeros x = x.zfill(max_len) print("x {}".format(x)) y = y.zfill(max_len) print("y {}".format(y)) print(y) # initialize the result result = '' # initialize the carry carry = 0 # Traverse the string for i in range(max_len - 1, -1, -1): r = carry r += 1 if x[i] == '1' else 0 r += 1 if y[i] == '1' else 0 result = ('1' if r % 2 == 1 else '0') + result carry = 0 if r < 2 else 1 # Compute the carry. if carry !=0 : result = '1' + result return result.zfill(max_len) |

**Using recursion**1 2 3 4 5 6 7 8 9 | def addBinary( a, b): if len(a)==0: return b if len(b)==0: return a if a[-1] == '1' and b[-1] == '1': return addBinary(addBinary(a[0:-1],b[0:-1]),'1')+'0' if a[-1] == '0' and b[-1] == '0': return addBinary(a[0:-1],b[0:-1])+'0' else: return addBinary(a[0:-1],b[0:-1])+'1' |

## No comments:

## Post a Comment