The Prime Number of Set Bits in Binary Representation problem asks you to count integers in [l, r] whose binary representation has a prime number of set bits. This easy coding problem combines bit counting (popcount) with primality checking. The math and bit manipulation interview pattern is demonstrated.
Amazon asks this to test combining two fundamental operations: counting set bits (Brian Kernighan's trick or bin().count('1')) and checking if a small count is prime. Since numbers in [1, 10^6] have at most 20 bits, the prime set count can only be {2,3,5,7,11,13,17,19} — a small fixed set.
Popcount + prime set membership. Precompute: prime_set = {2,3,5,7,11,13,17,19} (all primes ≤ 20 = max bit length of 10^6). For each n in [l, r]: count = bin(n).count('1'). If count in prime_set, increment result.
l=6, r=10.
Prime Number of Set Bits rewards precomputing: since the maximum number of bits is bounded (≤20), precompute all primes ≤20 into a set. Then the entire problem reduces to two O(1) operations per number. Practice similar "property of binary representation" problems: "count numbers with k set bits in range," "sum of set bits in range." These build fluency with bit counting.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Smallest Number With All Set Bits | Easy | Solve | |
| Number of Steps to Reduce a Number to Zero | Easy | Solve | |
| XOR Operation in an Array | Easy | Solve | |
| Sum of Two Integers | Medium | Solve | |
| Divide Two Integers | Medium | Solve |