Count the number of 1s in the binary representation of an integer (the Hamming weight; e.g. 13 = 1101 -> 3).
The elegant trick n & (n - 1) clears the lowest set bit; repeat until n is zero, counting iterations — this runs in O(number of set bits) rather than O(total bits). Built-ins (Integer.bitCount) exist and are worth mentioning.
public static int countSetBits(int n) {
int count = 0;
while (n != 0) { n &= (n - 1); count++; }
return count;
}function countSetBits(n) {
let count = 0;
while (n !== 0) { n &= (n - 1); count++; }
return count;
}def count_set_bits(n):
return bin(n).count('1')
# or Brian Kernighan:
# count = 0
# while n: n &= n - 1; count += 1Bit counting underlies feature-flag/permission masks, parity checks, and hashing — the n&(n-1) trick is a genuinely clever primitive.
Why is the n & (n-1) loop faster than checking every one of the 32 bits?