zoukankan      html  css  js  c++  java
  • 求二进制中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];
    }
  • 相关阅读:
    mongoDB在windows下安装和配置.
    node 中的定时器, nextTick()和setImmediate()的使用
    node 通过指令创建一个package.json文件
    node 中 npm报错 Error: ENOENT, stat 'C:UsersAdministratorAppDataRoaming pm'
    canvas之太阳系效果
    canvas之抒写文字
    canvas之绘制一张图片
    canvas之画一个三角形
    canvas之旋转一条线段
    unity3d 2d游戏制作的模式
  • 原文地址:https://www.cnblogs.com/guanling222/p/5306176.html
Copyright © 2011-2022 走看看