AlgoMaster Logo

Counting Bits

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Naive Approach

Intuition:

The naive approach involves iterating over each number from 0 to n and calculating the number of 1's in its binary representation. This can be achieved by repeatedly dividing the number by 2 and counting the remainder when divided by 2.

Code:

2. DP with Last Significant Bit

Intuition:

A powerful way to compute the number of 1-bits for all numbers from 0 to n is to use a simple observation about binary numbers:

For any number i:

  1. Right shift (i >> 1) removes the last bit. This means i >> 1 is simply i / 2 (integer division). So i >> 1 has the same bits as i except for the least significant bit.
  2. i & 1 extracts the last bit of i.
    • If it's odd → last bit is 1 → contributes +1
    • If it's even → last bit is 0 → contributes +0

This allows us to build the result using previously computed values, making the solution both efficient and elegant.

Instead of counting bits from scratch for every number, we reuse the results from smaller numbers.

Code:

Example Walkthrough:

Let’s compute res[0..7]

  • res[0] = 0
  • i = 1res[1] = res[0] + 1 = 1
  • i = 2res[2] = res[1] + 0 = 1
  • i = 3res[3] = res[1] + 1 = 2
  • i = 4res[4] = res[2] + 0 = 1
  • i = 5res[5] = res[2] + 1 = 2
  • i = 6res[6] = res[3] + 0 = 2
  • i = 7res[7] = res[3] + 1 = 3

3. Powers of two

Intuition:

This approach relies on understanding how binary representations behave around powers of two.

For any number x, if it lies in the interval: 2^m ≤ x < 2^(m+1)

then we can express it as: x = 2^m + k where 0 ≤ k < 2^m

What does this mean in terms of set bits?

  • 2^m has exactly one 1-bit, and it appears at position m.
  • The remaining part, k, contains whatever lower bits x has.

So the number of 1-bits in x becomes:

This allows us to reuse previously computed results from the range [0 … 2^m − 1].

We simply identify the most recent power of two, subtract it from x to get k, and use:

Code: