继续 计算一个整型数中的 1 bit 的个数。这里对 循环法 和 bit稀疏法 进行了验证, bit稀疏法比较好,循环的次数是 bit位为 1 的个数
- #include <stdio.h>
-
-
int bitcount(unsigned int n) //循环法
-
{
-
printf("bitcount...\n");
-
int count = 0;
-
while(n)
-
{
-
count += n & 0x1u;
-
n >>= 1;
-
}
-
printf("bit count = %d\n\n",count);
-
return count;
-
}
-
-
int bitcount2(unsigned int n) //稀疏法
-
{
-
int count = 0;
-
while(n)
-
{
-
count++;
-
n &= (n-1);
-
}
-
printf("bitcount2=%d\n",count);
-
return count;
-
}
-
int main(int argc, char *argv[])
-
{
-
unsigned int a = 9;
-
unsigned int b =19;
-
bitcount(a);
-
bitcount2(b);
-
return 0;
-
}
- ywx@yuweixian:~/yu/c/judge_1$ ./1xunhuan
-
bitcount...
-
bit count = 2
-
-
bitcount2=3
阅读(991) | 评论(0) | 转发(0) |