#include <stdio.h>
int countHowMuchOne( int number )
{
int count = 0;
while ( number )
{
number = number & ( number-1 );
++count;
}
return count;
}
int main()
{
int num = 11;
int count = 0;
count = countHowMuchOne( num);
printf("%d'binary format has %d bit 1 \n", num, count);
return 0;
}
// 解答
若一个数最右边一位为1,例如 x = 011011,x-1 = 011010,两者做&操作,会将最右边一位1消掉
若一个数最右边一位为0, 例如 x = 101100,x-1 = 101011,两者做&操作,同样会将最右边的一位1消掉
因为减一操作使得,原来的数x 的最低位从右向左直到遇到一个1,这些bit位都会取反,做&操作会将最右边的一位1消掉
#include <stdio.h>
int countHowMuchOne2( int number )
{
int count = 0;
int lastBit = 0;
while ( number )
{
lastBit = number & 1;
if ( lastBit )
{
++count;
}
number = number >> 1;
}
return count;
}
int main()
{
int num = 11;
int count = 0;
count = countHowMuchOne2( num);
printf("%d'binary format has %d bit 1 \n", num, count);
return 0;
}
// 解答 思路二:每次取最后一位和1与运算,若结果为1,说明末尾为1,否则末尾为0
// 扩展问题,如何判断一个数是否是2的n次方? 即: x ?= 1 << n
#include <stdio.h>
int func(int x)
{
if( (x&(x-1)) == 0 )
return 1;
else
return 0;
}
int main()
{
int x = 8;
printf("%d\n", func(x));
}
// 解答
一个数是2的n次方,则其二进制表示中最高位为1,其余位为0,而且只有一个1,那么 x&(x-1)必为0
// 其他关于位操作的例子
如何快速得到一个数的7倍? 答案: x << 3 - x