Convert Number to Binary Recursively

Convert decimal number to binary recursively.

IntermediatePhase 3 - Level 2: Advanced RecursionExample 6 of 10
convert-number-to-binary-recursively.py
1def to_binary(n):
2 # Base case
3 if n == 0:
4 return ""
5
6 # Recursive case
7 return to_binary(n // 2) + str(n % 2)
8
9# Test
10num = int(input("Enter a number: "))
11binary = to_binary(abs(num))
12if binary == "":
13 binary = "0"
14print(f"Binary: {binary}")

Output

Enter a number: 10
Binary: 1010

What's going on

Build binary from right to left.

Key Concepts:

Base case: n == 0, return empty
Get remainder (binary digit)
Recurse on quotient
Concatenate results