Skip to content

Commit 50f543e

Browse files
authored
Final_base_minus2.py
Fixes TheAlgorithms#9588 This code defines a decimal_to_base_minus_2 function that takes a decimal number as input and converts it to base -2.
1 parent 8c23cc5 commit 50f543e

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

Diff for: Final_base_minus2.py

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
def decimal_to_base_minus_2(decimal_number: int) -> str:
2+
"""
3+
Convert a decimal number to base -2.
4+
5+
Args:
6+
decimal_number (int): The decimal number to be converted.
7+
8+
Returns:
9+
str: The converted number in base -2.
10+
11+
Examples:
12+
>>> decimal_to_base_minus_2(13)
13+
'1101'
14+
15+
>>> decimal_to_base_minus_2(0)
16+
'0'
17+
18+
>>> decimal_to_base_minus_2(-10)
19+
'110'
20+
"""
21+
if decimal_number == 0:
22+
return "0"
23+
24+
result = ""
25+
26+
while decimal_number != 0:
27+
remainder = decimal_number % (-2)
28+
decimal_number = -(decimal_number // (-2))
29+
30+
if remainder < 0:
31+
remainder += 2
32+
decimal_number += 1
33+
34+
result = str(remainder) + result
35+
36+
return result

0 commit comments

Comments
 (0)