題目描述:
bitCount - returns count of number of 1's in word
Examples: bitCount(5) = 2, bitCount(7) = 3
Legal ops: ! ~ & ^ | + << >>
Max ops: 40
Rating: 4
解題思路(思路參考StackOverflow)
本題採取的是分而治之的思想:
Step1:將二進制數寫爲兩位一組,分別計算當前兩位中1的個數,並根據結果生成新的二進制數,舉例:01 11->01 10
Step2:和第一步結果相似,不同的是從兩位一組變成了四位一組,接下來的過程依次類推
爲了方便解釋接下來會引入一個具體的數,此處使用的是395
395的二進制表示:0000000110001011
由上述step1操作得到:
0000000110001011 (0 0 0 0 0 0 0 1 1 0 0 0 1 0 1 1)//395的二進制表示
0000000101000110 (0+0 0+0 0+0 0+1 1+0 0+0 1+0 1+1) = 00 00 00 01 01 00 01 10
通過step2得:
0000000101000110 ( 00 00 00 01 01 00 01 10 )//step1中的結果
0000000100010011 ( 00+00 00+01 01+00 01+10 ) = 0000 0001 0001 0011
依次類推:
0000000100010011 ( 0000 0001 0001 0011 )//step2中獲得結果
0000000100000100 ( 0000+0001 0001+0011 ) = 00000001 00000100
最後得出結果:
0000000000000101 ( 00000001+00000100 ) = 5
具體實現如下:
int bitCount(int x)
{
int count;
int tmpMask1=(0x55) | (0x55 << 8);
int mask1 = (tmpMask1) | (tmpMask1 << 16); //得到掩碼 01010101...01010101
int tmpMask2 = (0x33) | (0x33 << 8);
int mask2 = (tmpMask2) | (tmpMask2 << 16); //得到掩碼 00110011...00110011
int tmpMask3 = (0x0f) | (0x0f << 8);
int mask3 = (tmpMask3) | (tmpMask3 << 16);//得到掩碼 00001111...00001111
int mask4 = (0xff) | (0xff <<16); //得到掩碼 0000 0000 1111 1111 0000 0000 1111 1111
int mask5 = (0xff) | (0xff << 8);//得到掩碼: 0000 0000 0000 0000 1111 1111 1111 1111
count = (x & mask1) + ((x >> 1) &mask1);
count = (count & mask2) + ((count >> 2) & mask2);
count = (count & mask3) + ((count >> 4) & mask3);
count = (count & mask4) + ((count >> 8) & mask4);
count = (count & mask5) + ((count >> 16) & mask5);
return count;
}