beginner · bit manipulation · dynamic programming · shifts

Set bits for every number up to n

Problem

Build a table that, for every whole number i from 0 to n, holds how many 1 bits the binary form of i has. Aim for constant work per entry.

Constraints

  • 0 ≤ n ≤ 31 (visualization limit; the method works for any n)

Examples

n = 5 → [0, 1, 1, 2, 1, 2] — 0, 1, 10, 11, 100, 101.

Show the solution

Reuse the entry for i >> 1

i in binary is i >> 1 with one extra bit appended. So its count is the smaller number's count plus that last bit.

Why it is correct

Induction on i: bits[0] = 0. For i ≥ 1, the binary digits of i are those of i >> 1 followed by i & 1, so popcount(i) = popcount(i >> 1) + (i & 1). Since i >> 1 < i, bits[i >> 1] is already correct when bits[i] is computed.

Complexity

Time O(n), extra space O(n) for the output table. One shift, one AND and one addition per entry, n + 1 entries.

For contrast: Count the bits of every i with x &= x − 1 until zero. That costs O(n log n) time and O(n) space.

Edge cases

  • n = 0: [0].
  • Powers of two have exactly one bit.
  • Numbers of the form 2ᵏ − 1 have k bits.

Common mistakes

  • Using i − 1 instead of i >> 1 (the counts of neighbours are unrelated).
  • An off-by-one table of size n instead of n + 1.

Step through it

The solution in four languages

Each is checked against one shared set of cases and a randomized comparison with a brute-force reference.

namespace Bekadan.Dsa.Examples.Problems;
 
public static class BitCountsTable
{
    /// <summary>bits[i] = number of 1 bits of i, for 0 &lt;= i &lt;= n. O(n).</summary>
    public static int[] Table(int n)
    {
        var bits = new int[n + 1]; // bits[0] = 0
        for (int i = 1; i <= n; i++)
        {
            bits[i] = bits[i >> 1] + (i & 1); // i without its lowest bit, plus that bit
        }
        return bits;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Problems/BitCountsTable.cs

def table(n: int) -> list[int]:
    """bits[i] = number of 1 bits of i, for 0 <= i <= n. O(n)."""
    bits = [0] * (n + 1)
    for i in range(1, n + 1):
        bits[i] = bits[i >> 1] + (i & 1)  # i without its lowest bit, plus that bit
    return bits

Tested on CPython 3.14.0 · examples/python/dsa_examples/problems/bit_counts_table.py

package dev.bekadan.dsa.problems;
 
public final class BitCountsTable {
    private BitCountsTable() {
    }
 
    /** bits[i] = number of 1 bits of i, for 0 <= i <= n. O(n). */
    public static int[] table(int n) {
        int[] bits = new int[n + 1]; // bits[0] = 0
        for (int i = 1; i <= n; i++) {
            bits[i] = bits[i >> 1] + (i & 1); // i without its lowest bit, plus that bit
        }
        return bits;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/problems/BitCountsTable.java

#pragma once
 
#include <cstddef>
#include <vector>
 
namespace bekadan::dsa::problems {
 
// bits[i] = number of 1 bits of i, for 0 <= i <= n. O(n).
inline std::vector<int> bit_counts_table(std::size_t n) {
    std::vector<int> bits(n + 1, 0);
    for (std::size_t i = 1; i <= n; ++i) {
        bits[i] = bits[i >> 1] + static_cast<int>(i & 1);  // i without its lowest bit, plus that bit
    }
    return bits;
}
 
}  // namespace bekadan::dsa::problems

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/problems/bit_counts_table.hpp