版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/musechipin/article/details/80973621
题意是统计一个区间内有多少整数的二进制表示方法里的1的个数是质数。可以看一下数据规模在[1,10^6]之间,二进制位数不超过20位,可以直接枚举[1,20]的质数。
class Solution {
public:
int countPrimeSetBits(int L, int R) {
set<int> prim = { 2, 3, 5, 7, 11, 13, 17, 19 };
int result=0;
for (int i = L; i <= R; i++)
{
int count = 0;
int n = i;
while (n > 0)
{
count = count + n % 2;
n = n / 2;
}
result = result + prim.count(count);
}
return result;
}
};
还有一个暴力枚举的,速度特别快。应该是找到了某种和ascII码的映射关系,但是我没看懂,不放了。