Skip to content

adding negative binary base conversion algorithms #11213

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

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions conversions/int_to_negative_binary_base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
def decimal_to_negative_binary(number: int) -> int:
"""
a conversion algorithm from decimal
to negative binary base

https://en.wikipedia.org/wiki/Negative_base#:~:text=Binary-,Negabinary,-Ternary

>>> decimal_to_negative_binary(10)
11110
>>> decimal_to_negative_binary(-10)
1010
>>> decimal_to_negative_binary(-30)
100110
>>> decimal_to_negative_binary(30)
1100010
"""

if number == 0:
return 0
result_str = ""
while number != 0:
number, remainder = divmod(number, -2)
if remainder < 0:
number, remainder = number + 1, remainder + 2
result_str = str(remainder) + result_str
return int(result_str)


if __name__ == "__main__":
__import__("doctest").testmod()
24 changes: 24 additions & 0 deletions conversions/negative_binary_base_to_int.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
def negative_binary_to_int(negative_binary: int) -> int:
"""
a conversion algorithm from negative binary
base to decimal

https://en.wikipedia.org/wiki/Negative_base#:~:text=Binary-,Negabinary,-Ternary

>>> negative_binary_to_int(101110)
-38
>>> negative_binary_to_int(10111110)
-150
>>> negative_binary_to_int(100)
4
>>> negative_binary_to_int(110)
2
"""
negative_binary_str = str(negative_binary)
r = negative_binary_str[::-1]
res = [int(r[c]) * (-2) ** c for c in range(len(r))]
return sum(res)


if __name__ == "__main__":
__import__("doctest").testmod()