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).

Input: n = 11 (binary: 00000000000000000000000000001011)
Output: 3
Explanation: The binary representation has three '1' bits.
Input: n = 128 (binary: 00000000000000000000000010000000)
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.

public class Solution { public int hammingWeight(int n) { int count = 0; while (n != 0) { n &= (n - 1); // clears lowest set bit count++; } return count; } }
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.