Skip to content

Instantly share code, notes, and snippets.

@ioanzicu
Last active August 11, 2022 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ioanzicu/7b1c6c32b9dade1cef1e582e24930aac to your computer and use it in GitHub Desktop.
Save ioanzicu/7b1c6c32b9dade1cef1e582e24930aac to your computer and use it in GitHub Desktop.
67. Add Binary. Given two binary strings a and b, return their sum as a binary string.
def sum_binary(self, a: str, b: str) -> str:
# sort pythonic version
# return str(bin(int(a, 2) + int(b, 2)))[2:]
# long imperative version
if len(a) == 1 and a[0] == '0' and len(b) == 1 and b[0] == '0':
return '0'
m_len = max(len(a), len(b))
a = a.zfill(m_len)[::-1]
b = b.zfill(m_len)[::-1]
a = [int(num) for num in a]
b = [int(num) for num in b]
r = [0] * (len(a) + len(b))
for i in range(m_len):
if r[i] == 0:
if a[i] == 1 and b[i] == 1:
r[i] = 0
r[i + 1] = 1
elif (a[i] == 1 and b[i] == 0) or (a[i] == 0 and b[i] == 1):
r[i] = 1
elif r[i] == 1:
if a[i] == 1 and b[i] == 1:
r[i] = 1
r[i + 1] = 1
elif (a[i] == 1 and b[i] == 0) or (a[i] == 0 and b[i] == 1):
r[i] = 0
r[i + 1] = 1
# remove zeros
k = 0
r = r[::-1]
while r[k] == 0:
k += 1
r = r[k:]
r = [str(num) for num in r]
result = ''.join(r)
return result
res = sum_binary('111', '11')
print(res) # 1010
res = sum_binary('11', '1')
print(res) # 100
res = sum_binary('1010', '1011')
print(res) # 10101
res = sum_binary('0', '0')
print(res) # 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment