题目地址:
https://www.lintcode.com/problem/prime-number-of-set-bits-in-binary-representation/description
某个数二进制表示中 1 1 1的个数称为其“计算置位”。返回区间 [ L , R ] [L,R] [L,R]中的计算置位是素数的数的个数。其中 L ≤ R L\le R L≤R。
计算计算置位可以用lowbit来做。而计算置位的范围无非就是 0 ∼ 32 0\sim 32 0∼32,预处理一下即可。代码如下:
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) {
// write your code here
// 预处理素数判断,check[i]表示i是否是素数
boolean[] check = {false,
false, true, true, false, true,
false, true, false, false, false,
true, false, true, false, false,
false, true, false, true, false,
false, false, true, false, false,
false, false, false, true, false,
true, false};
int res = 0;
for (int i = L; i <= R; i++) {
if (check[cal(i)]) {
res++;
}
}
return res;
}
// 算n的计算置位
private int cal(int n) {
int res = 0;
while (n > 0) {
n -= lowbit(n);
res++;
}
return res;
}
private int lowbit(int x) {
return x & -x;
}
}
时间复杂度 O ( R − L ) O(R-L) O(R−L),空间 O ( 1 ) O(1) O(1)。