统计二进制中1的个数

来源:互联网 发布:单片机随机数程序 编辑:程序博客网 时间:2024/05/12 17:45

题目:输入一个整数,求该整数的二进制表达式中有多少个1.

例如,输入10,由于其二进制表示为1010,有两个1,因此输出 为2.


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


another solution is to lookup table, O(k), k is sizeof(int);
int countOf1(int n)
{
int c = 0;
if (n < 0)
{
c++;
n = n & (1 << (sizeof(int) * 8 - 1));
}
while (n != 0)
{
c += tab[n & 0xff];
n >>= 8;
}
return c;
}

0 0
原创粉丝点击