Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Convert Number to Binary Recursively

Build a binary representation recursively. Students divide by two, append remainder bits on return, and supply a visible zero for an empty base result.

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

In this one

  • Build bits on return
  • Use quotient and remainder two
  • Display literal zero

How it works

  1. 1

    Recurse on n // 2 until zero.

  2. 2

    Append each remainder as text during return.

  3. 3

    Replace an empty top-level result with the text zero.

Edge cases

Why convert the remainder with str?

Why convert the remainder with str?

String concatenation needs text, not an integer.

Does -5 show a minus sign?

Does -5 show a minus sign?

No. abs is used before conversion.

What's going on

Each call handles the remaining quotient before appending str(n % 2). That places the most significant bit first even though remainders are discovered from the right.

The base result is an empty string, not a printed zero. The caller changes that empty result to "0" for input zero. abs means negative inputs display the magnitude's binary digits, not a two's-complement encoding. Calls use stack space.

Why convert the remainder with str? String concatenation needs text, not an integer.

Does -5 show a minus sign? No. abs is used before conversion.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What is binary for five?

Pick an answer to check it.

Question 2

Why convert the remainder with str?

Pick an answer to check it.

Questions people ask

Why convert the remainder with str?

String concatenation needs text, not an integer.

Does -5 show a minus sign?

No. abs is used before conversion.

What is binary for five?

101.