Leetcode 762. Prime Number of Set Bits in Binary Representation
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.
Here’s a quick recap of the steps:
left
and right
? Can they be negative, or are they always positive?
left
and right
will be between 1
and 10^6
, inclusive.1
as a prime number?
1
is not considered a prime number.0 to 20
(highest count of set bits within the range 1 to 10^6) are prime.1s
.Here’s the implementation in Java:
import java.util.HashSet;
import java.util.Set;
public class Solution {
private static final Set<Integer> primes = new HashSet<>();
static {
primes.add(2);
primes.add(3);
primes.add(5);
primes.add(7);
primes.add(11);
primes.add(13);
primes.add(17);
primes.add(19);
}
private int countSetBits(int n) {
int count = 0;
while (n > 0) {
count += (n & 1);
n >>= 1;
}
return count;
}
public int countPrimeSetBits(int left, int right) {
int count = 0;
for (int i = left; i <= right; i++) {
if (primes.contains(countSetBits(i))) {
count++;
}
}
return count;
}
public static void main(String[] args) {
Solution sol = new Solution();
// Example test case
System.out.println(sol.countPrimeSetBits(6, 10)); // Output: 4
}
}
[left, right]
:
left
to right
is O(n), where n
is (right - left + 1).m
is the maximum possible value within the range, which is 10^6. Converting and counting bits involves iterating over the bits, resulting in O(log(m)).Combining these, the overall time complexity is O(n * log(m)), which simplifies to O(n * log(n)) for this specific problem with constraints, where n
is (right - left + 1) and m
is 10^6. This is efficient enough for the given problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?