int BitCount(unsigned int n)
{
unsigned int c =0 ; // 计数器
while (n >0)
{
if((n &1) ==1) // 当前位是1
++c ; // 计数器加1
n >>=1 ; // 移位
}
return c ;
}
2. 快速移位+计数
int BitCount2(unsigned int n)
{
unsigned int c =0 ;
while(n)
{
n &= (n -1) ;
c++;// 清除最低位的1
}
return c ;
}
算法-求二进制数中1的个数
最新推荐文章于 2022-11-16 22:58:01 发布