Skip to content

Instantly share code, notes, and snippets.

@jleeothon
Last active August 29, 2015 14:07
Show Gist options
  • Save jleeothon/31bf0970bd71dae98ebd to your computer and use it in GitHub Desktop.
Save jleeothon/31bf0970bd71dae98ebd to your computer and use it in GitHub Desktop.
Python: add binary numbers represented in a string recursively
def add_binary(n, m, c=False):
nb = n[-1] == "1" if n else False
mb = m[-1] == "1" if m else False
r = nb ^ mb ^ c
c = not nb and mb and c or nb and (mb or c)
n2 = n[:-1] if n else n
m2 = m[:-1] if m else m
if not n and not m:
return ""
return add_binary(n2, m2, c) + ("1" if r else "0")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment