Description
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). Return the result as an integer.
Examples
Input:
n = 11Output:
3Explanation:
The binary of 11 is 1011, which has three 1 bits.
Input:
n = 128Output:
1Explanation:
The binary of 128 is 10000000, which has one 1 bit.
Input:
n = 2147483645Output:
30Explanation:
2147483645 is 2^31 - 3, which in binary has all bits set except the second bit. This results in 30 set bits out of 31 total bits.
Constraints
- •
1 ≤ n ≤ 2³¹ - 1