Skip to content

Commit f159a33

Browse files
convert to the base minus 2 of a number (#9748)
* Fix: Issue 9588 * Fix: Issue 9588 * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Fix: Issue 9588 * Fix: Issue #9588 * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Fix: Issue #9588 * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Fix: Issue #9588 * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * fix: issue #9793 * fix: issue #9793 * fix: issue #9588 * [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>
1 parent 1b6c5cc commit f159a33

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Diff for: maths/base_neg2_conversion.py

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
def decimal_to_negative_base_2(num: int) -> int:
2+
"""
3+
This function returns the number negative base 2
4+
of the decimal number of the input data.
5+
6+
Args:
7+
int: The decimal number to convert.
8+
9+
Returns:
10+
int: The negative base 2 number.
11+
12+
Examples:
13+
>>> decimal_to_negative_base_2(0)
14+
0
15+
>>> decimal_to_negative_base_2(-19)
16+
111101
17+
>>> decimal_to_negative_base_2(4)
18+
100
19+
>>> decimal_to_negative_base_2(7)
20+
11011
21+
"""
22+
if num == 0:
23+
return 0
24+
ans = ""
25+
while num != 0:
26+
num, rem = divmod(num, -2)
27+
if rem < 0:
28+
rem += 2
29+
num += 1
30+
ans = str(rem) + ans
31+
return int(ans)
32+
33+
34+
if __name__ == "__main__":
35+
import doctest
36+
37+
doctest.testmod()

0 commit comments

Comments
 (0)