int count = 0;
while (n) {
if (n % 2 == 1) count++; // 或 n & 1
n >>= 1;
}
int count = 0;
while (n) {
n &= (n - 1); // 清除最低位 1
count++;
}
#include <stdio.h>
int main() {
unsigned int a = 15; // 1111b
// 右移法
int c1 = 0, t = a;
while (t) { if (t & 1) c1++; t >>= 1; }
// 按位與法
int c2 = 0; t = a;
while (t) { t &= t-1; c2++; }
printf("右移法: %d, 按位與法: %d\n", c1, c2); // 4, 4
return 0;
}
統計 1 的個數,**首選 n &= n-1**,配合 unsigned 類型,無符號右移次之,有符號右移禁用。