from line12 - Posted on August Mon 31st 4:34 PM (Never Expires) - Format: python - This is a modified post titled "add binary2". - See newer version(s) of this paste titled "try this one"
  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.         if s == 2:
  14.             res = '0' + res
  15.         if s == 3:
  16.             res = '1' + res
  17.         if s < 2:
  18.             res = str(s) + res
  19.         l -= 1
  20.     if carry:
  21.         return str(carry) + res
  22.     else:
  23.         return res
  24.  
  25. #from line 12, if I do not assign a viable, just use the expression, the result will be totally different.
  26. #could you tell me what's wrong with the second version ?
  27.  
  28. def addBinary(a,b):
  29.     length_dif = len(a) - len(b)#find length difference
  30.     if length_dif < 0:
  31.         a = '0'*(-length_dif )+ a#make two strings' length equal
  32.     if length_dif >= 0:
  33.         b = '0'*length_dif + b
  34.     l = len(a)-1
  35.     carry = 0
  36.     res = ''
  37.     while l >=0:
  38.  
  39.         if  int(a[l]) + int(b[l]) + carry == 2:
  40.             res = '0' + res
  41.         if  int(a[l]) + int(b[l]) + carry == 3:
  42.             res = '1' + res
  43.         if  int(a[l]) + int(b[l]) + carry < 2:
  44.             res = str( int(a[l]) + int(b[l]) + carry) + res
  45.         l -= 1
  46.     if carry:
  47.         return str(carry) + res
  48.     else:
  49.         return res

New Paste

Paste Options

Recent Pastes

22 hours ago

All transfers

4 days ago

Cloned Cards pre

10 days ago

Cvv PayPal banks

10 days ago

Cloned card and

11 days ago

DO ALL TRANSFERS

17 days ago

Cloned Cards and

17 days ago

Cloned Cards and

17 days ago

AB Authentic Sel

17 days ago

AB Authentic Sel

50 days ago

Cloned Cards pre