Skip to content

Excess 3 code #11001

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Oct 27, 2023
27 changes: 27 additions & 0 deletions bit_manipulation/excess_3_code.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
def excess_3_code(number: int) -> str:
"""
Find excess-3 code of integer base 10.
Add 3 to all digits in a decimal number then convert to a binary-coded decimal.
https://en.wikipedia.org/wiki/Excess-3

>>> excess_3_code(0)
'0b0011'
>>> excess_3_code(3)
'0b0110'
>>> excess_3_code(2)
'0b0101'
>>> excess_3_code(20)
'0b01010011'
>>> excess_3_code(120)
'0b010001010011'
"""
num = ""
for digit in str(max(0, number)):
num += str(bin(int(digit) + 3))[2:].zfill(4)
return "0b" + num


if __name__ == "__main__":
import doctest

doctest.testmod()