Algo-Sim › Matrix & Bit Manipulation

Counting Bits

Easy · Matrix & Bit Manipulation · step through it in Java, Python and C++ on your own input

Set-bit counts for every number 0..n in O(n): dp[i] = dp[i >> 1] + (i & 1) reuses the count of i without its last bit.

Problem

Given n, return an array ans of length n + 1 where ans[i] is the number of 1 bits in the binary form of i, for every i from 0 to n.

Constraints

Edge cases to test

Follow-up questions

Is there another recurrence?
dp[i] = dp[i & (i − 1)] + 1: drop the lowest set bit instead of the last bit. Same O(n).
Why is this better than calling popcount n times?
Popcount loops cost O(log n) each without hardware support; the DP reuses earlier answers for O(1) each.

Solution

Java

public int[] countBits(int n) {
    int[] dp = new int[n + 1];
    for (int i = 1; i <= n; i++) {
        dp[i] = dp[i >> 1] + (i & 1);
    }
    return dp;
}

Python

def count_bits(n):
    dp = [0] * (n + 1)
    for i in range(1, n + 1):
        dp[i] = dp[i >> 1] + (i & 1)
    return dp

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<int> countBits(int n) {
        vector<int> dp = vector<int>(n + 1);
        for (int i = 1; i <= n; i++) {
            dp[i] = dp[i >> 1] + (i & 1);
        }
        return dp;
    }
};

More Matrix & Bit Manipulation problems