• 求二进制中1的个数


    给定一个已知的整数n,求该数二进制1的个数

    仔细读题,可以发现,其实求该数二进制1的个数,只需依次判断最后一位数是否为1,然后循环右移即可。按照该思路写下如下所示代码:

     1 int count(unsigned char n)
     2 {
     3     int sum=0;
     4     while(n)
     5     {
     6         sum+=n&0x01;
     7         n>>=1;
     8     }
     9     return sum;
    10 }

    还可以按照求余法来实现

    int count(unsigned char n)
    {
        int sum=0;
        while(n)
        {
            if(n%2==1)
                sum++;
            n/=2;
        }
        return sum;
    }

    1中所述方法始终是循环移动8位,

    int count(unsigned char n)
    {
        int sum=0;
        while(n)
        {
            n&=(n-1);
            sum++;
        }
        return sum;
    }
    int table[256]={
                0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,               
                1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,                
                1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,               
                2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,                
                1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,                
                2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,                
                2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,                
                3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,               
                1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,                
                2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,                
                2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,                
                3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,               
                2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,                
                3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,                
                3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,                
                4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, 
                };
    
    int count(unsigned char n)
    {
        return table[n];
    }
  • 相关阅读:
    LeetCode Medium:15. 3Sum
    LeetCode Medium:12. Integer to Roman
    LeetCode Medium: 11. Container With Most Water
    TypeError: unsupported operand type(s) for /: 'map' and 'int'
    【C#】课堂知识点#4
    【C#】课堂知识点#3
    【统计与建模】R语言基本操作
    【题解】表达式的值
    【题解】瑞士轮
    【题解】道路游戏
  • 原文地址:https://www.cnblogs.com/guanling222/p/5306176.html
Copyright © 2020-2023  润新知