This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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