C程序设计语言(第二版) 2-9
时间:2010-07-15 来源:carolaif
2-9 bitcount()函数:统计x中值为1的二进制位数
#include <stdio.h>
int bitcount(unsigned x){
int b;
for(b=0;x!=0;x>>=1)
if(x&1)
b++;
return b;
}
int main ()
{
unsigned x=10;//将x声明为无符号整型数是为了保证将x右移时,无论该程序在什么机器上运行,左边空出的位数都用0(而不是符号位)填补。
int count;
count=bitcount(x);
printf("%d\n",count);
return 0;
}
表达式x&=(x-1)可以删除x中最右边值为1的一个二进制位。用这一方法重写bitcount函数,可以加快执行速度。
int bitcount(unsigned x){
int b;
for(b=0;x!=0;x&=(x-1))
b++;
return b;
}
相关阅读 更多 +










