# Bitwise Algorithm 3: Count Bits

### Problem

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

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

### 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; }