Count Binary Ones
easySave
Bit Manipulation
Given a non-negative integer n, return the count of '1's in its binary representation. This is also known as the Hamming weight or the population count.
Example 1
Input
[ 10 ]
Output
2
Explanation. The binary representation of 10 is 1010, which has two '1's.
Example 2
Input
[ 31 ]
Output
5
Explanation. The binary representation of 31 is 11111, which has five '1's.
Example 3
Input
[ 0 ]
Output
0
Explanation. The binary representation of 0 is 0, there are no '1's.
Example 4
Input
[ 255 ]
Output
8
Explanation. The binary representation of 255 is 11111111, which has eight '1's.
Follow-up: Can you implement the function without converting the integer to a binary string directly?
Constraints:
The input integer n is a non-negative integer.
- Views
- 3