Prime Number of Set Bits in Binary Representation (LeetCode 762): Solution and Explanation
Given a range [left, right], count the numbers whose binary form has a prime number of 1 bits. For left = 6, right = 10 the answer is 4: 6, 7, 9 and 10 have 2, 3, 2 and 2 set bits, while 8 has only one.
Intuition
The range holds at most 10,001 numbers, so there is no need for anything clever about which numbers to visit. The work per number is counting its 1 bits and asking whether that count is prime.
The second question looks like it needs a primality test, but the counts are tiny. Every value is at most 10^6, which is below 2^20, so a number has at most 20 set bits. The only primes up to 20 are 2, 3, 5, 7, 11, 13, 17 and 19.
A fixed list of eight primes fits in one integer. Set bit k of a mask exactly when k is prime: that gives binary 10100010100010101100, which is 665772. Asking whether bits is prime becomes reading bit bits of the mask, (mask >> bits) & 1, and that value is already the 0 or 1 to add to the count.
Approach: Popcount with a prime bitmask
- Set
mask = 665772, which has bits 2, 3, 5, 7, 11, 13, 17 and 19 turned on. - For each
xfromlefttoright, count its set bits with a built-in popcount or thex &= x - 1loop. - Add
(mask >> bits) & 1tocount: it is 1 exactly whenbitsis prime. - Return
count.
Step-by-step example
left = 6, right = 10
- 6 = 110 has 2 set bits. Bit 2 of the mask is 1, so count = 1.
- 7 = 111 has 3 set bits. Bit 3 is 1, so count = 2.
- 8 = 1000 has 1 set bit. Bit 1 of the mask is 0 because 1 is not prime, so count stays 2.
- 9 = 1001 has 2 set bits, count = 3.
- 10 = 1010 has 2 set bits, count = 4. Return 4.
Code: Python, Java, C++
1class Solution:
2 def countPrimeSetBits(self, left: int, right: int) -> int:
3 mask = 665772 # bits 2, 3, 5, 7, 11, 13, 17, 19 are set
4 count = 0
5 for x in range(left, right + 1):
6 bits = bin(x).count('1')
7 count += (mask >> bits) & 1
8 return count1class Solution {
2 public int countPrimeSetBits(int left, int right) {
3 int mask = 665772; // bits 2, 3, 5, 7, 11, 13, 17, 19 are set
4 int count = 0;
5 for (int x = left; x <= right; x++) {
6 int bits = Integer.bitCount(x);
7 count += (mask >> bits) & 1;
8 }
9 return count;
10 }
11}1class Solution {
2public:
3 int countPrimeSetBits(int left, int right) {
4 int mask = 665772; // bits 2, 3, 5, 7, 11, 13, 17, 19 are set
5 int count = 0;
6 for (int x = left; x <= right; x++) {
7 int bits = __builtin_popcount(x);
8 count += (mask >> bits) & 1;
9 }
10 return count;
11 }
12};Time and space complexity
O(right - left)
Each number gets one popcount, which is constant time for a 32-bit integer, and one shift and AND.
O(1)
Only the mask and the counter are stored.
Other approaches
Set of small primes (time O(right - left), space O(1))
Keep {2, 3, 5, 7, 11, 13, 17, 19} in a hash set and test membership. Same complexity and slightly easier to read.
Trial division on the count (time O((right - left) * sqrt(20)), space O(1))
Check primality of each bit count by dividing by 2 up to its square root. Works for any range of counts, but it is extra code for numbers that never exceed 20.
Common mistakes
- Treating 1 as prime. A power of two has exactly one set bit and must not be counted.
- Forgetting that the range is inclusive, so right itself is checked too.
- Building the mask with the wrong positions. Bit k of the mask stands for the number k, so the lowest bit (k = 0) and bit 1 must both be 0.
- Counting bits by converting to a string in a hot loop in languages where that allocates. It still passes, but a popcount instruction or x &= x - 1 is cheaper.
Frequently asked questions
Why does the mask only need 20 bits?
right is at most 10^6, which is less than 2^20 = 1,048,576. So no number in range has more than 20 set bits, and 19 is the largest prime that can occur.
Where does 665772 come from?
It is 2^2 + 2^3 + 2^5 + 2^7 + 2^11 + 2^13 + 2^17 + 2^19. Each power puts a 1 at the position of one prime.
How does x &= x - 1 count bits?
Subtracting 1 flips the lowest 1 bit to 0 and the zeros below it to 1, so the AND clears exactly one set bit. The loop runs once per set bit.