LeetCode | 762. Prime Number of Set Bits in Binary Representation


题目:

Given two integers L and R, find the count of numbers in the range [L, R] (inclusive) having a prime number of set bits in their binary representation.

(Recall that the number of set bits an integer has is the number of 1s present when written in binary. For example, 21 written in binary is 10101 which has 3 set bits. Also, 1 is not a prime.)

Example 1:

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)

Example 2:

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.

题意思路:

输入L和R形成闭区间[L, R],区间中的任意数字,其二进制形式中包含的1的数量为质数个,则计数器加1,最终输出该区间中所有符合这个条件的总计数,也就是计数器的值。


题目中提示输入的L,R的差别值不超过10^6,L-R不超过10000,计数器不用考虑超大的情况,10^6的范围说明可能存在的数字中包含1的最大数量,如输入10^6,则log_2(10^6) < 30,那么即使是该范围中包含1最多的数,也不会超过30个,则初始化只需要列出30之内的质数作为备选即可。


代码:

int countPrimeSetBits(int L, int R) {
        set<int> primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29};
        int count = 0;
        for(int cur = L; cur <= R; cur++)
        {
            bitset<30> tmp(cur);
            if(primes.count(tmp.count()))
                count++;
        }
        return count;
    }

其中,使用了bitset这个类,让所有初始化的值转换为二进制格式,用自带的count函数就可以计算出1的个数。






猜你喜欢

转载自blog.csdn.net/iLOVEJohnny/article/details/79817821