Numbers with Even 1s in Binary
Print numbers whose binary form has even number of 1s.
AdvancedPhase 2 - Level 5: Logical Loop CombinationsExample 6 of 12
numbers-with-even-1s-in-binary.py
1# Print numbers2print("Numbers with even 1s in binary:")3for num in range(1, 21):4 # Count 1s in binary5 binary = bin(num)[2:] # Remove '0b' prefix6 count_ones = binary.count('1')78 if count_ones % 2 == 0:9 print(f"{num} (binary: {binary})", end=" ")10print()
Output
Numbers with even 1s in binary: 1 (binary: 1) 2 (binary: 10) 4 (binary: 100) ...
What's going on
Convert to binary and count 1s.
Key Concepts:
Use bin() to convert to binary
Count occurrences of '1'
Check if count is even
🔗Related Content
- 📖
Phase 2 - Learn Concepts
Review Phase 2 concepts and explanations
- 📝
Phase 2 - Quiz
Test your Phase 2 understanding with quiz questions
- 💻
Phase 2 - All Practice Problems
Explore all practice problems for Phase 2
- 🎓
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- 🧠
Logic Building Overview
Learn about the complete logic building curriculum