Given a positive integer n, return the number of set bits in its binary representation (also known as the Hamming weight).
n = 113n = 1281The expression n & (n−1) always clears the lowest set bit of n. This is because subtracting 1 from n flips all bits from the lowest set bit down to bit 0 (turning that set bit into 0 and all lower 0-bits into 1s). The AND then cancels out all those flipped bits. By repeating until n becomes 0, we count exactly how many set bits existed — one per iteration. Brian Kernighan's trick runs in O(k) where k is the popcount, not O(log n) like a naive bit-by-bit scan.
You can check all 32 bits one by one with a shift and a mask. That always takes 32 steps, even when only a few bits are set.
Look at n −1 in binary: the lowest 1 bit of n turns into 0, and every bit below it turns into 1. So n AND n −1 is n with its lowest set bit removed. Repeat until n becomes 0, counting each step. The loop runs exactly once per 1 bit.
N AND n −1 removes the lowest set bit. This trick appears in many bit problems.
Run the animation above on your own input, or watch the 1:26 video explanation of Number of 1 Bits with a dry run and Java code.