Here is the complete solution using the Brian Kernighan trick:
function hammingWeight(n)
count := 0
while n > 0
n := n & (n - 1) // Flip rightmost 1 bit to 0
count := count + 1
return count
For (binary ), the loop runs 3 times: , , . The count is 3. Time complexity: where is the number of 1 bits. Space: .