Given two integers left and right, return _thecount of numbers in the
inclusive range _[left, right]having aprime 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: left =6, right =10Output: 4Explanation:
6->110(2 set bits,2is prime)7->111(3 set bits,3is prime)8->1000(1 set bit,1is not prime)9->1001(2 set bits,2is prime)10->1010(2 set bits,2is prime)4 numbers have a prime number of set bits.
Input: left =10, right =15Output: 5Explanation:
10->1010(2 set bits,2is prime)11->1011(3 set bits,3is prime)12->1100(2 set bits,2is prime)13->1101(3 set bits,3is prime)14->1110(3 set bits,3is prime)15->1111(4 set bits,4is not prime)5 numbers have a prime number of set bits.
For each number in the range [left, right], count the number of set bits (1s) in its binary representation (call it cnt). If cnt is a prime number, increment the answer. Since the maximum number of set bits for numbers up to 10^6 is at most 20, we can precompute all primes up to 20 in a primes set and test membership in O(1).
#include<vector>#include<unordered_set>usingnamespace std;
intcountPrimeSetBits(int left, int right) {
unordered_set<int> primes = {2,3,5,7,11,13,17,19};
int ans =0;
for (int x = left; x <= right; ++x) {
int cnt = __builtin_popcount(x);
if (primes.count(cnt)) ++ans;
}
return ans;
}
import java.util.*;
classSolution {
publicintcountPrimeSetBits(int left, int right) {
Set<Integer> primes = Set.of(2,3,5,7,11,13,17,19);
int ans = 0;
for (int x = left; x <= right; ++x) {
int cnt = Integer.bitCount(x);
if (primes.contains(cnt)) ++ans;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
funcountPrimeSetBits(left: Int, right: Int): Int {
val primes = setOf(2,3,5,7,11,13,17,19)
var ans = 0for (x in left..right) {
val cnt = Integer.bitCount(x)
if (cnt in primes) ans++ }
return ans
}
1
2
3
4
5
6
7
8
defcountPrimeSetBits(left: int, right: int) -> int:
primes = {2,3,5,7,11,13,17,19}
ans =0for x in range(left, right+1):
cnt = bin(x).count('1')
if cnt in primes:
ans +=1return ans
1
2
3
4
5
6
7
8
9
10
11
fncount_prime_set_bits(left: i32, right: i32) -> i32 {
let primes = [2,3,5,7,11,13,17,19];
letmut ans =0;
for x in left..=right {
let cnt = x.count_ones();
if primes.contains(&(cnt asi32)) {
ans +=1;
}
}
ans
}
1
2
3
4
5
6
7
8
9
10
11
12
13
exportfunctioncountPrimeSetBits(left: number, right: number):number {
constprimes=newSet([2,3,5,7,11,13,17,19]);
letans=0;
for (letx=left; x<=right; ++x) {
letcnt=0, y=x;
while (y>0) {
cnt+=y&1;
y>>=1;
}
if (primes.has(cnt)) ans++;
}
returnans;
}