您的位置:首页 > 其它

LeetCode | 762. Prime Number of Set Bits in Binary Representation 简单题 二进制技巧题

2018-01-18 17:53 363 查看
Giventwo integers L and R, find the count of numbers in therange [L, R] (inclusive) having a prime number of set bits in their binaryrepresentation.(Recallthat the number of set bits an integer has is the number of 1s present when written in binary. Forexample, 21 written in binary is10101 which has 3 set bits. Also, 1 is not a prime.)Example1:Input: L = 6, R = 10
Output: 4
Explanation:
6 -> 110 (2 set bits, 2 is prime)
7 -> 111 (3 set bits, 3 is prime)
9 -> 1001 (2 set bits , 2 is prime)
10->1010 (2 set bits , 2 is prime)
Example2:Input: L = 10, R = 15
Output: 5
Explanation:
10 -> 1010 (2 set bits, 2 is prime)
11 -> 1011 (3 set bits, 3 is prime)
12 -> 1100 (2 set bits, 2 is prime)
13 -> 1101 (3 set bits, 3 is prime)
14 -> 1110 (3 set bits, 3 is prime)
15 -> 1111 (4 set bits, 4 is not prime)
Note:1.      L, R will be integers L <= R in the range [1, 10^6].2.      R - L will be at most 10000.题目问你,R到L之间有多少个数的二进制的1的和为质数,这就是一道简单题,循环R到L,然后去其二进制里面的1的个数的和,然后判断这个和是否为质数,至于如何判断和是否为质数,只要遍历2~sqrt(num)里面的数看他是否是num的因数就行了,假如没有这样的数那么num就是质数。
至于如何取一个数的二进制位,有两种方法,一种是除2取余法,一种是右移取Num和1做与门操作,然后看结果,这里使用的是第二种方法,具体使用哪种方法看你的心情了class Solution {
public:
bool isPrere(int num)
{
int count = 0;
while (num != 0)
{
if (num & 1 == 1) count++;
num >>= 1;
}
if (count == 1) return false;
for (int i = 2; i <= sqrt(count); i++)
{
if (count%i == 0) return false;
}
return true;
}

int countPrimeSetBits(int L, int R) {

int count = 0;
for (int i = L; i <= R; i++)
{
if (isPrere(i)) count++;
}
return count;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: