bitcount(unsigned x):
- 统计x中值为1的二进制位数
- 将x声明为无符号类型是为了保证将x右移时,无论该程序在什么机器上运行,左边空出的位都是0(而不是符号位)填补。
1、通过右移操作实现
#include <stdio.h>
//通过右移操作实现
int bitcount(unsigned x) {
int b;
for(b = 0; x != 0; x >>= 1) {
if(x & 01) {
b++;
}
}
return b;
}
int main(void) {
int count = bitcount(17);
printf("1的总数: %d\n", count);
return 0;
}
2、通过x &= (x-1)实现
x &= (x-1):可以删除x中最右边值为1的一个二进制位。
//通过 x &= (x-1)实现
int bitcount2(unsigned x) {
int countx = 0;
while(x) {
countx++;
x &= (x-1);
printf("x: %d\n", x);
}
return countx;
}
x & (x-1)用法补充:求x是否是2的n次方
//判断是否是2的次幂
/*
x = 16 10000
x-1 = 15 01111
& 00000
*/
int isPower2(int x) {
if((x&(x-1)) == 0)
return 1;
else
return 0;
}