位运算---整数的二进制表达中有多少个1

来源:互联网 发布:寂寞聊天软件 编辑:程序博客网 时间:2024/05/22 12:08

【题目】

  给定一个32位整数n,可正、可负、可0.返回该整数二进制表达中1的个数。

【基本思路】

  最简单的方法。整数n每次进行无符号右移一位,检查最右边的bit是否为1来进行统计即可。

下面是使用c++实现的代码:

int count1(int n){    unsigned int num = (unsigned)n;    int res = 0;    while(num != 0)    {        res += num & 1;        num = num >> 1;    }    return res;}

上述方法最坏情况下要进行32次循环,接下来介绍两个循环次数只与1的个数有关的解法。

int count2(int n){    int res = 0;    while(n != 0)    {        n -= n & (~n + 1);        res++;    }    return res;}

每次进行n -= n & (~n + 1)操作时就是移除最右边1的过程。n & (~n + 1)的含义就是得到n中最右边的1。例如,n = 01000100, n & (~n + 1) = 00000100, n - n & (~n + 1) = 01000000。

int count3(int n){    int res = 0;    while(n != 0)    {        n = n & (n-1);        res++;    }    return res;}

n = n & (n-1)这也是移除最右侧1的过程。例如: n = 01000100, n-1 = 01000011, n & (n-1) = 01000000。

阅读全文
2 0