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.
Definition: A set bit is a bit that has a value of 1.
Example:
Input: left = 6, right = 10
Output: 4
Explanation:
6 -> 110 (2 set bits, which is prime)
7 -> 111 (3 set bits, which is prime)
8 -> 1000 (1 set bit, not prime)
9 -> 1001 (2 set bits, which is prime)
10 -> 1010 (2 set bits, which is prime)
Note:
left
<= right
<= 10^61 ≤ left, right ≤ 10^6
left
and right
?
left
and right
can range from 1
to 10^6
.10^6
can be represented in binary with at most 20 bits.left
to right
, count the set bits, and check if this count is a prime number. If yes, increase the result count.#include <iostream>
#include <vector>
#include <bitset>
// Function to check if a number is prime
bool isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) return false;
}
return true;
}
// Function to count the number of set bits in binary representation
int countSetBits(int n) {
return std::bitset<21>(n).count(); // 21 to handle up to 20 bits
}
int countPrimeSetBits(int left, int right) {
int count = 0;
for (int i = left; i <= right; i++) {
int setBits = countSetBits(i);
if (isPrime(setBits)) {
count++;
}
}
return count;
}
int main() {
int left = 6;
int right = 10;
std::cout << countPrimeSetBits(left, right) << std::endl; // Output: 4
return 0;
}
countSetBits
function uses bitset which operates in O(1) for a fixed number representation (21 bits in this case).isPrime
function, in worst case, performs operations proportional to the square root of n
(up to 20 in this scenario).left
to right
is O(n)
, where n
is the length of the range.Therefore, the overall time complexity is O(n * sqrt(m)), where n is the range [left, right]
and m
is the maximum number of set bits (in this case, up to 20, a constant). This simplifies the overall complexity to O(n) given the 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?