我觉得应该是要预处理,把素数表先求出来,我之前背过模板,let me try。。。我估计了一下如果LR都是小于10^6的话,就和1024*1024差不多在同一个数量级,也就是至多有差不多20个1左右,那就可以不用判断素数,直接把20以内的素数都标出来就行了
class Solution {
public int countPrimeSetBits(int L, int R) {
int[] isPrime = {0,0,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0};
int res = 0;
while( L <= R ){
int coun = 0;
int tmp = L;
while( tmp != 0 ){
if( ( tmp & 1 ) == 1 )coun++;
tmp >>= 1;
}
if( isPrime[ coun ] == 1)res++;
L ++;
}
return res;
}
}
跑的有点慢,我瞅了一眼,Java竟然有方法来统计一个整型数中1的个数,真是神奇,这个方法就是Integer.bitCount( L )
再交一次
class Solution {
public int countPrimeSetBits(int L, int R) {
int[] isPrime = {0,0,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0};
int res = 0;
while( L <= R ){
if( isPrime[ Integer.bitCount( L )] == 1 )res ++ ;
L ++;
}
return res;
}
}