>>// 15 = 00001111b
15 >> 1 = 7 (00000111b)
15 >> 2 = 3 (00000011b)
&常用於遮罩、檢測特定位。1 & 1 = 1,其餘為 0。
int count_bits_shift(unsigned int x) {
int cnt = 0;
while (x) {
if (x & 1) cnt++;
x >>= 1;
}
return cnt;
}
int count_bits_bk(unsigned int x) {
int cnt = 0;
while (x) {
x &= (x - 1); // 清除最低位 1
cnt++;
}
return cnt;
}
BK 法迴圈次數等於 1 的個數,對稀疏 1 極快。
#include <stdio.h>
int main() {
unsigned int n;
printf("輸入整數: ");
scanf("%u", &n);
printf("右移法: %d\n", count_bits_shift(n));
printf("BK 法: %d\n", count_bits_bk(n));
return 0;
}
&/>> 特性。__builtin_popcount (GCC/Clang) 或 std::popcount (C++20)。