📚 Brian Kernighan's Algorithm
The operation
n & (n - 1) removes the lowest
(rightmost) set bit:
// n - 1 flips all bits from rightmost 1 to the end
// ANDing clears the rightmost 1
// Example: n = 12 (1100)
// n - 1 = 11 (1011)
// n & (n-1) = 8 (1000)
// This is used to count set bits efficiently!
count = 0;
while (n > 0) {
n = n & (n - 1);
count++;
}