Count total set bits in all numbers from 1 to n

Pattern: Counting bits

medium

Count each bit position separately. In 0..n, bit b repeats in blocks of 2^(b+1) numbers, half off and half on. Full blocks give 2^b ones each; the last partial block gives whatever passes the halfway point.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Given n, return the total number of set bits in the binary forms of all numbers from 1 to n. For example, n = 4 gives 5 (1, 1, 2 and 1 bits for 1, 2, 3 and 4), and n = 17 gives 35. The answer is returned as a 64-bit number.

This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name countSetBits is this guide's own.

Think first

  • Write 0 to 15 in binary. How does the last column behave? The second-to-last?
  • How many full repeats of a column's pattern fit in 0..n?
  • What does the leftover part add?

Hints

    Brute force, and why it fails

    Count bits of every number: O(n log n), too slow for n near 10⁹. Per-bit counting is O(log n).

    The key insight

    Instead of going number by number, go column by column. Each column is a simple repeating pattern whose total can be written down directly.

    Dry run

    0000 
    0011 
    0102 
    0113 
    1004 

    n = 4. The numbers 0 to 4 are 000, 001, 010, 011, 100. That is n + 1 = 5 numbers.

    Step 1 of 4

    The plan

    total = 0, block = 2
    while block / 2 <= n:
        full = (n + 1) / block, rest = (n + 1) mod block
        total = total + full * (block / 2) + max(0, rest - block / 2)
        block = block * 2
    return total
    

    Complexity

    Time
    O(log n)
    Space
    O(1)

    One step per bit position.

    Edge cases

    • n = 0: 0.
    • n = 2^k - 1: exactly k × 2^(k-1).
    • Large n: use 64-bit totals.
    I've built my logic, show the code

    Java

    class Solution {
        public long countSetBits(int n) {
            long total = 0;
            for (long block = 2; block / 2 <= n; block <<= 1) {   // bit b repeats in blocks of 2^(b+1): half 0s, half 1s
                long full = (n + 1L) / block;                       // complete blocks give block / 2 ones each
                long rest = (n + 1L) % block;                       // the partial block gives max(0, rest - block / 2)
                total += full * (block / 2) + Math.max(0, rest - block / 2);
            }
            return total;
        }
    }

    C++

    class Solution {
    public:
        long long countSetBits(int n) {
            long long total = 0;
            for (long long block = 2; block / 2 <= n; block <<= 1) {   // bit b repeats in blocks of 2^(b+1)
                long long full = (n + 1LL) / block;                     // complete blocks give block / 2 ones each
                long long rest = (n + 1LL) % block;                     // the partial block gives max(0, rest - block / 2)
                total += full * (block / 2) + max(0LL, rest - block / 2);
            }
            return total;
        }
    };

    Python

    class Solution:
        def countSetBits(self, n: int) -> int:
            total, block = 0, 2
            while block // 2 <= n:                  # bit b repeats in blocks of 2^(b+1): half 0s, half 1s
                full, rest = divmod(n + 1, block)   # complete blocks, and how far into the next one
                total += full * (block // 2) + max(0, rest - block // 2)
                block <<= 1
            return total

    Common mistakes

    • Using n instead of n + 1 (the numbers start at 0).
    • Stopping the loop one bit too early.
    • Computing in 32 bits, where the total can overflow.

    Similar problems