leetcode-762-Prime Number of Set Bits in Binary Representation

时间:2022-05-16
本文章向大家介绍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.

要完成的函数:

int countPrimeSetBits(int L, int R) 

说明:

1、这道题给了两个界限,一个左界限,一个右界限,要求在左右界限的闭区间之内,对每一个数进行判断,最终返回符合条件的数值的个数。

判断的方法是,将每一个数转化为二进制表示,数一下有多少个1,然后看一下1的个数是不一个素数,比如10的二进制是1010,有2个1,2是一个素数,满足条件。

2、明白了规则之后,代码就很容易写了,我们迭代处理,对每个数都进行判断,逐位地右移取出,数一下有多少个1,然后再对个数进行判断就好了。

由于题目限制左界限和右界限在[1,10^6]之内,所以每个数都可以用有符号型整数来表示,也就是说二进制中1的个数最多不会超过32,所以我们可以直接定义一个长度32的vector,里面存储1-32每个数的素数判断情况,这样子处理会快很多。

代码如下:

    int countPrimeSetBits(int L, int R) 
    {
        int i=L,j,count,total=0;
        vector<int>primevec={0,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,1,0};
        while(i<=R)
        {
            count=0;
            j=i;
            while(j)
            {
                count+=(j&1);//取出最后一位,加到count里面去
                j>>=1;//j不断右移
            }
            if(primevec[count-1])
                total++;
            i++;
        }
        return total;
    }

上述代码十分简洁,实测15ms,beats 83.46% of cpp submissions。