Skip to content
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

convert to the base minus 2 of a number #9748

Merged
merged 20 commits into from
Oct 5, 2023
Merged
Show file tree
Hide file tree
Changes from 17 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
40 changes: 40 additions & 0 deletions maths/base_neg2_conversion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
def decimal_to_negative_base_2(num: int) -> int:
"""
This function returns the number negative base 2
of the decimal number of the input data.

Args:
int: The decimal number to convert.

Returns:
int: The negative base 2 number.

Examples:
>>> decimal_to_negative_base_2(0)
0
>>> decimal_to_negative_base_2(-19)
111101
>>> decimal_to_negative_base_2(4)
100
>>> decimal_to_negative_base_2(7)
11011
"""
if num == 0:
return 0
ans = ""
while num != 0:
rem = num % -2
num = num // -2
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

if rem < 0:
rem += 2
num += 1

ans = str(rem) + ans

return int(ans)


if __name__ == "__main__":
import doctest

doctest.testmod()