Write a function that takes the binary representation of a positive integer and returns the number of set bits it has (also known as the Hamming weight).
Output: 3
Explanation: The binary representation has three '1' bits.
Output: 1
Explanation: Only one '1' bit at position 7.
The trick n & (n-1) clears the lowest set bit of n. By repeatedly applying this until n becomes 0, we count exactly how many 1-bits n has — each iteration removes one 1-bit.
- Initialize count to 0.
- While n is not zero, perform
n = n & (n-1)to clear the lowest set bit. - Increment count on each iteration.
- Return count when n reaches 0.
Complexity Analysis:
Time complexity: O(k) where k is the number of set bits — each iteration removes one 1-bit.
Space complexity: O(1) — constant extra space.