zoukankan      html  css  js  c++  java
  • 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。

  • 相关阅读:
    [No0000199]设计模式总结
    [No0000197]Windows用户都应该知道的运行命令
    [No000017F]如何监控注册表的修改
    [No0000196]一文读懂Java 11的ZGC为何如此高效
    [No0000195]NoSQL还是SQL?这一篇讲清楚
    [No0000194]聊聊 Chrome DevTools 中你可能不知道的调试技巧
    [No000018A]改善C#程序的建议11-20
    [No000018C]Vim清除上次的搜索高亮结果-Vim使用技巧(1)
    [No000018D]Vim快速注释/取消注释多行的几种方法-Vim使用技巧(2)
    [No000018E]Vim快速跳转任意行、任意列以及高亮显示当前行、当前列方法-Vim使用技巧(3)
  • 原文地址:https://www.cnblogs.com/chenjx85/p/9040916.html
Copyright © 2011-2022 走看看