Last active
August 29, 2015 14:07
-
-
Save jleeothon/31bf0970bd71dae98ebd to your computer and use it in GitHub Desktop.
Python: add binary numbers represented in a string recursively
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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