二进制有效位数内质数
原题在这里
概述题意:给一个区间,问区间内有多少个数字的二进制有效位数是质数。
1.因为数据合适,所以直接暴力:
class Solution { public: int countPrimeSetBits(int left, int right) { /* 2,3,5,7,11,13 */ int ans = 0; while (left <= right) { int x = left++, y = 0; while (x) y += x & 1, x >>= 1; ans += (y == 2) + (y == 3) + (y == 5) + (y == 7) + (y == 11) + (y == 13) + (y == 17) + (y == 19) + (y == 23) + (y == 29); } return ans; } };
2.优化处理
1.有效位统计改为x&=x-1
2.质数判断:
因为只有2,3,5...19,这几个数字,换成二进制数字表示:665772
那么只需要进行 该数与有效位数与运算 , 非0即有效
code:
class Solution { public: int countPrimeSetBits(int left, int right) { /* 2,3,5,7,11,13,17,19 */ int ans = 0; while (left <= right) { int x = left++, y = 0; while (x) ++y, x &= x - 1; ans += ((1 << y & 665772) != 0); } return ans; } };
【Over】

浙公网安备 33010602011771号