Created
April 7, 2016 18:08
-
-
Save Deathnerd/0cf26dd66ebbaf8880e3458242d0f8b8 to your computer and use it in GitHub Desktop.
Python to increment and decrement a binary string without converting to int. Decr does not take into account underflows
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 incr(bit_string): | |
carry = False | |
bits = list(bit_string[::-1]) | |
for i, bit in enumerate(bits): | |
carry = bit != "0" | |
if bit == "0": | |
bits[i] = "1" | |
break | |
else: | |
bits[i] = "0" | |
if carry: | |
bits.append("1") | |
return "".join(bits[::-1]) | |
def decr(bit_string): | |
bits = list(bit_string[::-1]) | |
for i, bit in enumerate(bits): | |
if bit == "1": | |
bits[i] = "0" | |
break | |
else: | |
bits[i] = "1" | |
return "".join(bits[::-1]) | |
print incr("101") | |
print incr("1111") | |
print decr("101") | |
print decr("110") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment