Prime Number of Set Bits in Binary Representation - Problem
Given two integers left and right, return the count of numbers in the inclusive range [left, right] having a prime number of set bits in their binary representation.
Recall that the number of set bits an integer has is the number of 1's present when written in binary.
For example, 21 written in binary is 10101, which has 3 set bits.
Input & Output
Example 1 — Basic Range
$
Input:
left = 6, right = 10
›
Output:
4
💡 Note:
6 = 110₂ (2 bits, prime), 7 = 111₂ (3 bits, prime), 8 = 1000₂ (1 bit, not prime), 9 = 1001₂ (2 bits, prime), 10 = 1010₂ (2 bits, prime). So 4 numbers have prime set bits.
Example 2 — Small Range
$
Input:
left = 10, right = 15
›
Output:
5
💡 Note:
10 = 1010₂ (2 bits), 11 = 1011₂ (3 bits), 12 = 1100₂ (2 bits), 13 = 1101₂ (3 bits), 14 = 1110₂ (3 bits), 15 = 1111₂ (4 bits, not prime). Numbers 10,11,12,13,14 have prime set bits.
Example 3 — Single Number
$
Input:
left = 4, right = 4
›
Output:
0
💡 Note:
4 = 100₂ has 1 set bit, and 1 is not prime, so result is 0.
Constraints
- 1 ≤ left ≤ right ≤ 106
- 0 ≤ right - left ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input Range
Given left=6, right=10
2
Convert & Count
Convert each number to binary and count 1-bits
3
Check Prime
Count numbers where set bit count is prime
Key Takeaway
🎯 Key Insight: Only need to check if bit counts 1-32 are prime since integers have at most 32 bits
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code