4 回答

TA貢獻1786條經驗 獲得超11個贊
在我看來,“最佳”解決方案是另一個程序員(或兩年后的原始程序員)可以閱讀而沒有大量評論的解決方案。你可能想要一些已經提供的最快或最聰明的解決方案,但我更喜歡可讀性而不是聰明。
unsigned int bitCount (unsigned int value) {
unsigned int count = 0;
while (value > 0) { // until all bits are zero
if ((value & 1) == 1) // check lower bit
count++;
value >>= 1; // shift bits, removing lower bit
}
return count;
}
如果你想要更快的速度(假設你記錄好以幫助你的繼任者),你可以使用表查找:
// Lookup table for fast calculation of bits set in 8-bit unsigned char.
static unsigned char oneBitsInUChar[] = {
// 0 1 2 3 4 5 6 7 8 9 A B C D E F (<- n)
// =====================================================
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, // 0n
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, // 1n
: : :
4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, // Fn
};
// Function for fast calculation of bits set in 16-bit unsigned short.
unsigned char oneBitsInUShort (unsigned short x) {
return oneBitsInUChar [x >> 8]
+ oneBitsInUChar [x & 0xff];
}
// Function for fast calculation of bits set in 32-bit unsigned int.
unsigned char oneBitsInUInt (unsigned int x) {
return oneBitsInUShort (x >> 16)
+ oneBitsInUShort (x & 0xffff);
}
雖然這些依賴于特定的數據類型大小,因此它們不具備可移植性。但是,由于許多性能優化無論如何都不可移植,這可能不是問題。如果你想要便攜性,我會堅持使用可讀的解決方案。
添加回答
舉報