Problem 762 · LeetCode 762(opens in a new tab)
Prime Number of Set Bits in Binary Representation
EasyBit manipulation
You get two whole numbers, left and right. Write each number from left to right (both included) in binary and count its 1 bits, also called its set bits.
Return how many of those numbers have a prime count of set bits. For example, 13 is 1101 in binary: 3 set bits, and 3 is prime, so 13 counts.
Example 1
Input: left = 30, right = 34 Output: 3 Why: 31, 33, 34 have 5, 2, 2 set bits; 30 has 4 and 32 has 1
2 more examples and the constraints
Example 2
Input: left = 1, right = 5 Output: 2 Why: 3 (11) and 5 (101) have 2 set bits; 1, 2, 4 have only 1
Example 3
Input: left = 7, right = 7 Output: 1 Why: 7 is 111, and 3 set bits is a prime count
Constraints
- 1 ≤ left ≤ right ≤ 1,000,000
- right − left ≤ 10,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Count bits, test for primeO((r − l)·log r)
- Popcount and a prime maskO(r − l)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,001 numbers | Verdict |
|---|---|---|---|
| Count bits, test for prime | O((r − l)·log r) | Clear; passes easily | |
| Popcount and a prime mask | O(r − l) | Best; one lookup each |
l = left, r = right; a number up to r has about log r bits.
Edge cases to test
- Count of 1. Powers of two such as 32 have one set bit, and 1 is not prime.
- A single number. left = right = 7 checks only 7 and gives 1.
- Starting at 1. left = 1, right = 1 gives 0.
- Near the top. 999,990 to 1,000,000 still has at most 20 bits per number, so primes up to 19 are enough.
Common mistakes
- Treating 1 as prime, which counts every power of two.
- Stopping the prime list at 7 or 13; counts up to 19 can occur.
- Leaving out
right: the range includes both ends.
How to talk through it
- 1Clarify. Are both ends included? How large can right get, and so how many bits can a number have?
- 2Give the direct approach. Count bits by shifting, test the count with trial division.
- 3Bound the count. Below 2²⁰ there are at most 20 bits, so only eight prime counts are possible.
- 4Code the mask. Popcount, then one shift and one AND into a fixed mask of primes.
- 5Test out loud. Run a power of two (count 1) and a single-number range before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?