ADD BINARY - Posted on August Mon 31st 2:21 PM (Never Expires) - Format: python - This is a modified post titled "with level". - See newer version(s) of this paste titled "add binary2"
  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.         print(s)
  14.         if s == 2:
  15.             res = '0' + res
  16.             carry = 1
  17.         if s == 3:
  18.             res = '1' + res
  19.             carry = 1
  20.         if s < 2:
  21.             res = str(s) + res
  22.             carry = 0
  23.         l -= 1
  24.     if carry:
  25.         return str(carry) + res
  26.     else:
  27.         return res
  28.  
  29. '''
  30. def addBinary(a,b):
  31.    length_dif = len(a) - len(b)
  32.    if length_dif < 0:
  33.        a = '0'*length_dif + a
  34.    if length_dif >= 0:
  35.        b = '0'*length_dif + b
  36.    l = len(a)-1
  37.    carry = 0
  38.    res = ''
  39.    while l >=0:
  40.  
  41.        if  int(a[l]) + int(b[l]) + carry == 2: #but if I use parameter: in round 2, the int(a[l]) + int(b[l]) are still int(a[0]) + int(b[0]), only carry == 1.
  42.            res = '0' + res
  43.            carry = 1
  44.        if  int(a[l]) + int(b[l]) + carry == 3:
  45.            res = '1' + res
  46.            carry = 1
  47.        if  int(a[l]) + int(b[l]) + carry < 2:
  48.            res = str(s) + res
  49.            carry = 0
  50.        l -= 1
  51.    if carry:
  52.        return str(carry) + res
  53.    else:
  54.        return res
  55.  
  56. s = addBinary('1010', '1011')
  57. print(s)
  58. '''

New Paste

Paste Options

Recent Pastes

29 days ago

EARN PAYPAL IN A

30 days ago

QUICK CASH VIA

30 days ago

ATM cloned cards

30 days ago

ATM cloned cards

30 days ago

ATM cloned cards

30 days ago

ATM cloned cards

36 days ago

A MONEY MAKING B

36 days ago

A MONEY MAKING B

36 days ago

A MONEY MAKING B

36 days ago

A MONEY MAKING B