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 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
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
🔗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