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.
1def to_binary(n):2 # Base case3 if n == 0:4 return ""56 # Recursive case7 return to_binary(n // 2) + str(n % 2)89# Test10num = 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
Recurse on n // 2 until zero.
- 2
Append each remainder as text during return.
- 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.
๐Related Content
- ๐
Phase 3 - Learn Concepts
Review Phase 3 concepts and explanations
- ๐
Phase 3 - Quiz
Test your Phase 3 understanding with quiz questions
- ๐ป
Phase 3 - All Practice Problems
Explore all practice problems for Phase 3
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum