Counting Bits

Count the 1s in the binary form of every number from 0 to n, reusing the count of a smaller number.

Given a whole number n that is 0 or more, return an array bits of length n + 1. For every i from 0 to n, the entry bits[i] must hold the number of 1s in the binary form of i.

Example 1
Input: n = 2
Output: [0, 1, 1]
Explanation: in binary, 0 is 0, 1 is 1 and 2 is 10, so they hold zero, one and one 1s.
Example 2
Input: n = 5
Output: [0, 1, 1, 2, 1, 2]
Explanation: 3 is 11 and 5 is 101, so both hold two 1s.
Solution

The Idea

A computer stores every number as a row of bits, each 0 or 1. Each bit stands for a power of two. The rightmost bit, at position 0, is worth 1, the bit at position 1 is worth 2, the next is worth 4, and so on. So 5 is written 101, which is 4 + 1, and it holds two 1s.

Take Example 2, with n = 5. In binary, the numbers 0 to 5 are 0, 1, 10, 11, 100 and 101, holding 0, 1, 1, 2, 1 and 2 ones. That is the output [0, 1, 1, 2, 1, 2]. For six numbers, counting by eye is easy. For a large n, reading the bits of every number one by one repeats a lot of work. Can the count for one number come from a count we already have?

Look at the picture below. Each row shows a number with its binary digits at positions 2, 1 and 0, and the box with the orange outline in each row is the last bit, at position 0.

The numbers 0 to 5 in binary, with bit positions 2, 1 and 0. For 5, binary 101, the number without the last bit is 2 (10) and the last bit is 1. The count of 1s in 2 is already known, 1, so 5 has 1 + 1 = 2.

Cross off the last bit, and the bits that are left form a smaller number, shown in the column "without the last bit". In the orange row, 5 is 101. Without its last bit it is 10, which is 2, and the bit that was crossed off is 1.

The teal row for 2 sits higher up. Since the rows are filled from the top down, its count is already there: 2 holds one 1. So 5 holds that one, plus its last bit, 1 + 1 = 2. The arrow labelled "already known" shows that step. The other rows work the same way. Take 4, which is 100: without the last bit it is 2 again, and its last bit is 0, so 4 holds 1 + 0 = 1.

So, written from 0 upward, each new count is one earlier count plus one bit. Filling the counts in that order, where each one reuses a count already written, is called dynamic programming. Here the table being filled is the answer itself: bits[i] is the number of 1s in i.

Solution Approach

Turning that idea into code means seeing why counting each number on its own is slower, then settling how Java splits off the last bit and which order fills the array safely. Removing the lowest 1 bit, instead of the last bit, is an optional alternative.

Counting each number on its own

Why not count the 1s of every number separately? A loop can check the bits of i one at a time, and Java's Integer.bitCount(i) also returns the number of 1s in i. A number up to n has about log2 n bits, so 1,000 has ten. Checking each bit of each number takes O(n log n) steps in all, while reusing an earlier count takes one step per number.

Splitting off the last bit

How does Java give us the number without its last bit, and that bit itself? A Java int is 32 bits in two's complement, the form in which position 31, the leftmost bit, marks a negative number. Every number here is 0 or more, so that bit is 0.

The shift i >> 1 moves every bit one position to the right, and the bit at position 0 falls off: 5 >> 1 is 2. The bitwise AND i & 1 compares i with 1 bit by bit and keeps a 1 only where both have one. The number 1 has its single 1 at position 0, so i & 1 is the last bit of i: 5 & 1 is 1. Put together:

bits[i] = bits[i >> 1] + (i & 1)

The order to fill the array

Is bits[i >> 1] always ready when bits[i] needs it? For any i of 1 or more, i >> 1 is half of i, rounded down, so it is smaller. A loop that counts i up from 1 has therefore filled it already. The start, bits[0] = 0, needs no line of its own, because a new int array in Java begins with every entry at 0.

Removing the lowest 1 bit (optional)

Does the smaller number have to be the one without the last bit? Another choice is i with its lowest 1 bit cleared. Subtracting 1 from i turns that lowest 1 into 0 and the 0s to its right into 1s, so i & (i - 1) clears it. For 6, which is 110, 6 & 5 is 110 & 101 = 100, which is 4.

That smaller number holds exactly one 1 fewer, so bits[i] = bits[i & (i - 1)] + 1, and bits[6] is bits[4] + 1 = 2. This trick is often named after Brian Kernighan. In a test run, this version matched Integer.bitCount for every number from 0 to 100,000.

Java Solution

The method countBits works in these steps:

  1. First, create the answer array with int[] bits = new int[n + 1], one entry for each number from 0 to n. Java fills it with 0s, so bits[0] is already right.
  2. Then a loop moves i from 1 up to n.
  3. Inside the loop, set bits[i] to bits[i >> 1], the count for i without its last bit, plus (i & 1), the last bit itself.
  4. Once the loop has filled every entry, the method returns bits.

The main method runs both examples, n = 0 and n = 16, then compares every count up to 100,000 with Integer.bitCount.

Java
import java.util.Arrays;

public class CountingBits {

    public static int[] countBits(int n) {
        int[] bits = new int[n + 1];               // bits[0] stays 0
        for (int i = 1; i <= n; i++) {
            bits[i] = bits[i >> 1] + (i & 1);      // count without the last bit, plus that bit
        }
        return bits;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(countBits(2)));
        System.out.println(Arrays.toString(countBits(5)));
        System.out.println(Arrays.toString(countBits(0)));
        System.out.println(Arrays.toString(countBits(16)));

        int[] big = countBits(100000);
        boolean same = true;
        for (int i = 0; i <= 100000; i++) {
            same &= big[i] == Integer.bitCount(i);
        }
        System.out.println("same as Integer.bitCount for 0 to 100000: " + same);
    }
}

Running it prints:

Output
[0, 1, 1]
[0, 1, 1, 2, 1, 2]
[0]
[0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1]
same as Integer.bitCount for 0 to 100000: true

With n = 5 the method returns [0, 1, 1, 2, 1, 2], the same counts as the rows of the picture. For n = 0 the loop never runs, and [0] comes back with its single entry.

Look at the end of the fourth line. The number 15, which is 1111, holds four 1s, but 16, which is 10000, holds just one. Its count comes from 8, which comes from 4, then 2, then 1, each holding a single 1. The last line shows that all 100,001 counts agree with Integer.bitCount.

The parentheses in (i & 1) are needed. Java applies + before &, so bits[i >> 1] + i & 1 means (bits[i >> 1] + i) & 1. A test run of that version with n = 5 returned [0, 1, 1, 0, 1, 0], which is wrong for 3 and 5.

Complexity

The method does the same small amount of work for each number from 1 to n.

  • Time: O(n), because the loop fills each of the n entries after bits[0] with one shift, one AND, one array read and one addition.
  • Space: O(1) besides the output, because the bits array of n + 1 entries is the answer itself, and the loop keeps only i.