Files
Python/conversions/negative_binary_base_to_int.py
Margaretandpre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> 1eb999e293 adding negative binary base conversion algorithms (#11213)
* adding negative binary base conversion algorithms

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* fixing bugs

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2026-09-16 08:59:07 +02:00

25 lines
631 B
Python

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()