Loading problem…
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).
Example 1
Input: n = 11
Output: 3
Explanation: 11 in binary is 1011, which has three 1 bits.
Example 2
Input: n = 128
Output: 1
Explanation: 128 in binary is 10000000, a single 1 followed by seven 0s.
Example 3
Input: n = 1
Output: 1
Explanation: 1 in binary is just 1, so it has one set bit.
The expression n & (n - 1) clears the lowest set bit of n. Repeatedly apply it and count how many times you can before n becomes 0 — that count is exactly the number of set bits.
Run checks all cases above. Submit evaluates all test cases.