Monday, July 26, 2021

LintCode 1046 · Prime Number of Set Bits in Binary Representation.java

public class Solution {
/**
* @param L: an integer
* @param R: an integer
* @return: the count of numbers in the range [L, R] having a prime number of set bits in their binary representation
*/
public int countPrimeSetBits(int L, int R) {
// handle corner cases
int counter = 0;
for (int i = L; i <= R; i++) {
if (isPrimeSetBits(i)) {
counter++;
}
}
return counter;
}
private boolean isPrimeSetBits(int i) {
int counter = 0;
while (i > 0) {
if (i % 2 == 1) {
counter++;
}
i /= 2;
}
return isPrime(counter);
}
private boolean isPrime(int number) {
if (number < 2) {
return false;
}
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}

No comments:

Post a Comment