#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