兩數對應位不同 ⇔ XOR 該位為 1。
diff_bits = popcount(a ^ b)。
#includeint main() { int m = 1999; // 011111001111 int n = 2299; // 100011111011 int x = m ^ n; // 111100110100 int count = 0; while (x) { count += x & 1; x >>= 1; } printf("%d\n", count); // 7 return 0; }
int diff_bits(int a, int b) {
return __builtin_popcount(a ^ b);
}