问题描述:
找出一定范围内的数字数量,这些数字满足其二进制表示有质数个1
思路:思路很直接,我们需要做三件事:(1)判断质数 (2)查看二进制有几个一 (3)遍历整个区间
代码如下(低配版):
class Solution {
public int countPrimeSetBits(int left, int right) {
int counter=0;
for(int i=left; i<=right; i++){
if (isPrime(countOne(i))) counter++;
}
return counter;
}
private int countOne(int n){
String str=Integer.toBinaryString(n);
int counter=0;
for(int i=0; i<str.length(); i++){
if(str.charAt(i)=='1') counter++;
}
return counter;
}
private boolean isPrime(int n){
if((n==0)||(n==1)) return false;
for(int i=2; i<=Math.floor(Math.sqrt(n)); i++){ //check from 2 to sqrt(n)
if(n%i==0) return false;
}
return true;
}
}
高配版:
class Solution {
public int countPrimeSetBits(int left, int right) {
int counter=0;
for(int i=left; i<=right; i++){
if (isPrime(countOne(i))) counter++;
}
return counter;
}
private int countOne(int n){
int counter=0;
while(n>0){
if((n&1)==1) counter++;
n=n>>>1; //right shift n by 1 bit
}
return counter;
}
private boolean isPrime(int n){ //at most 20 bits
if((n==2)||(n==3)||(n==5)||(n==7)||(n==11)||(n==13)||(n==17)||(n==19)) return true;
else return false;
}
}
时间复杂度: O(lga+lgb+lgc+…+lgn)