Count the number of set bits (1s) in the binary representation of an unsigned integer. Watch how the n &= (n - 1) trick efficiently drops the lowest set bit in each iteration.
fun hammingWeight(n: Int): Int { var num = n; var count = 0 while (num != 0) { num = num and (num - 1) count++ } return count }
The operation n &= (n - 1) is a clever bit manipulation trick that clears the lowest set bit
(rightmost 1) in the binary representation of n. By repeatedly applying this operation until n becomes 0,
we can count exactly how many 1 bits were present.
When you subtract 1 from a number, all the bits after the rightmost 1 (including that 1) get flipped:
n = 1011 (binary), then n - 1 = 1010n & (n-1) = 1011 & 1010 = 1010, the rightmost 1 is clearedcount = 0n > 0:
n &= (n - 1) to clear the lowest set bitcountcount (the number of times we cleared a bit)
Where k is the number of set bits. This algorithm runs in time proportional to the number of 1 bits,
not the total number of bits (32). For sparse numbers (few 1s), this is much faster than checking every bit position.