762. Prime Number of Set Bits in Binary Representation
Given two integers L
and R
, find the count of numbers in the range [L, R]
(inclusive) having a prime 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. Also, 1 is not a prime.)
首先就是要先將 L 到 R 中間的數字轉為二進位表示,接著再根據轉換後有幾個 1 來得到 count,
最後再判斷 count 是否為質數,最後再回傳總共有幾個 count 為質數。
class Solution {
public int countPrimeSetBits(int L, int R) {
int count = 0;
for(int i=L; i<=R; i++) {
if(isLegal(i)) count++;
}
return count;
}
private boolean isLegal(int number) {
int count = 0;
char[] binaryNums = Integer.toBinaryString(number).toCharArray();
for(char binaryNum : binaryNums) {
if(binaryNum == '1') count++;
}
if(count == 1) return false;
for(int i=2; i<count; i++) {
if(count%i == 0) return false;
}
return true;
}
}