Skip to content

Commit 0a43d07

Browse files
authored
Create Base(-2)_conversion.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 1243138 commit 0a43d07

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

Base(-2)_conversion.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
def decimal_to_base_minus_2(n):
2+
if n == 0:
3+
return "0"
4+
5+
result = ""
6+
7+
while n != 0:
8+
remainder = n % (-2)
9+
n = -(n // (-2))
10+
11+
if remainder < 0:
12+
remainder += 2
13+
n += 1
14+
15+
result = str(remainder) + result
16+
17+
return result
18+
19+
# Example usage:
20+
decimal_number = 13
21+
base_minus_2 = decimal_to_base_minus_2(decimal_number)
22+
print(f"{decimal_number} in base -2 is {base_minus_2}")

0 commit comments

Comments
 (0)