题目地址:
https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation/
给定一个正整数区间 [ L , R ] [L,R] [L,R],问其有多少个整数的二进制表示 1 1 1的个数是素数。
代码如下:
import java.util.Arrays;
public class Solution {
public int countPrimeSetBits(int L, int R) {
boolean[] isPrime = new boolean[32];
build(isPrime);
int res = 0;
for (int i = L; i <= R; i++) {
if (isPrime[count1(i)]) {
res++;
}
}
return res;
}
private int count1(int x) {
int count = 0;
while (x != 0) {
x -= lowbit(x);
count++;
}
return count;
}
private int lowbit(int x) {
return x & -x;
}
private void build(boolean[] isPrime) {
Arrays.fill(isPrime, true);
isPrime[0] = isPrime[1] = false;
for (int i = 2; i < isPrime.length; i++) {
if (!isPrime[i]) {
continue;
}
for (int j = 2; j * i < isPrime.length; j++) {
isPrime[j * i] = false;
}
}
}
}
时间复杂度 O ( R − L ) O(R-L) O(R−L),空间 O ( 1 ) O(1) O(1)。