Problem

Count the number of 1s in the bit representation of the given integer.

For example, given the number 6, the bit representation is 0110, which contains two 1s, so the answer is 2.

Algorithm

In the previous tutorial we learned how to clear the lowest bit of a number. We can use that algorithm to solve this problem. All we need to do is count how many times we need to clear the lowest bit of a number, until we are left with the number 0.

Here is the code in java:

public static int countBits(int n, int k) {
    int count = 0;
    while(0 != n) {
        n = clearLowestBit(n);
        count++;
    }
    return count;
}
Be Sociable, Share!