Prime Number of Set Bits in Binary Representation
算一下bit为1的个数, 然后看下个数是不是prime.
class Solution {
public int countPrimeSetBits(int L, int R) {
int count = 0;
for(int i = L; i <= R; i++) {
if(isPrime(countBit(i)))
count++;
}
return count;
}
private int countBit(int n) {
int res = 0;
for(int i = 0 ; i < 32; i++) {
if((n & (1 << i)) != 0)
res++;
}
return res;
}
public boolean isPrime(int number) {
if(number < 2)
return false;
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 2; i < sqrt; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}