Logic Building
def to_binary(n):
# Base case
if n == 0:
return ""
# Recursive case
return to_binary(n // 2) + str(n % 2)
# Test
num = int(input("Enter a number: "))
binary = to_binary(abs(num))
if binary == "":
binary = "0"
print(f"Binary: {binary}")Output
Enter a number: 10 Binary: 1010
Build binary from right to left.
Key Concepts:
- Base case: n == 0, return empty
- Get remainder (binary digit)
- Recurse on quotient
- Concatenate results