Skip to content

Commit 4e9df4a

Browse files
committed
Fix: Issue 9588
1 parent 922d6a8 commit 4e9df4a

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

maths/base_neg2_conversion.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import doctest
2+
def decimal_to_negative_base_2(n):
3+
"""
4+
This function returns the number negative base 2 of the decimal number of the input data.
5+
6+
Args:
7+
n (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 n == 0:
23+
return 0
24+
ans = ""
25+
while n != 0:
26+
rem = n % -2
27+
n = n // -2
28+
if rem < 0:
29+
rem += 2
30+
n += 1
31+
32+
ans = str(rem) + ans
33+
34+
return int(ans)
35+
36+
if __name__ == "__main__":
37+
doctest.testmod()

0 commit comments

Comments
 (0)