Count Bits
Given a non-negative integer n, write a function to return the number of '1' bits in its binary representation (also known as the Hamming weight).
For example, given the integer n = 11, which is 1011 in binary, the number of '1' bits is 3.
[ 11 ]
Explanation. The binary representation of 11 is 1011, which has three '1' bits.
[ 128 ]
Explanation. The binary representation of 128 is 10000000, which has one '1' bit.
[ 255 ]
Explanation. The binary representation of 255 is 11111111, which has eight '1' bits.
[ 0 ]
Explanation. The binary representation of 0 is 0, which has no '1' bits.
Follow-up: Can you implement this in linear time complexity without using any built-in bit manipulation functions?
The input must be a non-negative integer.
- Views
- 3