统计整数二进制表示中1的个数

三种比较好的方法:

(1)复杂度为 

int test(int n)
{
    int count=0;
    while(n != 0){
        count += n&1;
        n >>= 1;
    }
    return count;
}

(2)

int test(int n)
{
    int count=0;
    while(n != 0){
        n &= n-1;
        count ++;
    }
    return count;
}
(3)

int test(int n)
{
    n = (n&0x55555555) + ((n>>1)&0x55555555);
    n = (n&0x33333333) + ((n>>2)&0x33333333);
    n = (n&0x0f0f0f0f) + ((n>>4)&0x0f0f0f0f);
    n = (n&0x00ff00ff) + ((n>>8)&0x00ff00ff);
    n = (n&0x0000ffff) + ((n>>16)&0x0000ffff);
 
    return n;
}

比如这个例子,143的二进制表示是10001111,这里只有8位,高位的0怎么进行与的位运算也是0,所以只考虑低位的运算,按照这个算法走一次

+---+---+---+---+---+---+---+---+
| 1 | 0 | 0 | 0 | 1 | 1 | 1 | 1 |   <---143
+---+---+---+---+---+---+---+---+
|  0 1  |  0 0  |  1 0  |  1 0  |   <---第一次运算后
+-------+-------+-------+-------+
|    0 0 0 1    |    0 1 0 0    |   <---第二次运算后
+---------------+---------------+
|        0 0 0 0 0 1 0 1        |   <---第三次运算后,得数为5
+-------------------------------+

基本思路:先算出相邻两位1的个数,然后在算出相邻四位的个数,递推到最后32位。


### 计算整数二进制表示1的数量 对于计算整数在其二进制形式中有多少个`1`,存在多种方法可以实现这一目标。下面介绍几种常见的算法。 #### 取余法 通过不断对给定数值除以2并检查其余数是否为1统计二进制位上的1的数目。这种方法简单直观但效率较低,因为每次迭代都需要执行一次除法操作[^4]。 ```python def count_binary_ones_remainder(num): count = 0 while num != 0: remainder = num % 2 if remainder == 1: count += 1 num //= 2 return count ``` #### 移位法 利用按位右移运算符逐步处理每一位直到所有的比特都被访问过为止。此方式同样适用于正负整数,在某些情况下可能比取模更高效一些[^3]。 ```c++ #include <iostream> using namespace std; int main() { int value; cin >> value; unsigned int uValue = static_cast<unsigned int>(value); int count = 0; for (unsigned int i = 0; i < sizeof(int)*8 ; ++i){ if((uValue>>i)&1) count++; } cout << "count=" << count << endl; } ``` #### 高级计算法——Brian Kernighan’s Algorithm 这是一种更为高效的解决方案,它基于这样一个事实:当我们将一个数字与其减去一的结果做按位与(&&)时会清除掉最右边的那个'1'。因此只要这个过程不返回零就可以持续减少原值直至其变为零,并在此过程中计数被清除了几次即可得到最终结果[^5]。 ```cpp // C++ implementation of Brian Kernighan's algorithm to find the number of set bits in an integer. int countSetBits(unsigned int n) { int count = 0; while(n){ n &= (n-1); // Clearing the least significant bit set count++; } return count; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值