add binary2 - Posted on August Mon 31st 2:46 PM (Never Expires) - Format: python - This is a modified post titled "ADD BINARY". - See newer version(s) of this paste titled "from line12"
  1. #leetcode67 add binary
  2. def addBinary(a,b):
  3.     length_dif = len(a) - len(b)#find length difference
  4.     if length_dif < 0:
  5.         a = '0'*length_dif + a#make two strings' length equal
  6.     if length_dif >= 0:
  7.         b = '0'*length_dif + b
  8.     l = len(a)-1
  9.     carry = 0
  10.     res = ''
  11.     while l >=0:
  12.         s = int(a[l]) + int(b[l]) + carry #If I assign a virable to the sum, the function will work.
  13.         carry = s // 2
  14.         if s == 2:
  15.             res = '0' + res
  16.         if s == 3:
  17.             res = '1' + res
  18.         if s < 2:
  19.             res = str(s) + res
  20.         l -= 1
  21.     if carry:
  22.         return str(carry) + res
  23.     else:
  24.         return res

New Paste

Paste Options

Recent Pastes

12 days ago

EARN PAYPAL IN A

13 days ago

QUICK CASH VIA

13 days ago

ATM cloned cards

13 days ago

ATM cloned cards

13 days ago

ATM cloned cards

13 days ago

ATM cloned cards

19 days ago

A MONEY MAKING B

19 days ago

A MONEY MAKING B

19 days ago

A MONEY MAKING B

19 days ago

A MONEY MAKING B