VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-total-set-bits-in-all-numbers-from-1-to-n/

⇱ Count total set bits in first N Natural Numbers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count total set bits in first N Natural Numbers

Last Updated : 28 Nov, 2025

Given a positive integer n, determine the total number of set bits (1s) in the binary representation of all numbers from 1 to n, inclusive.

Examples:

Input: n = 3
Output:  4
Explanation: Numbers from 1 to 3: {1, 2, 3}
Binary Representation of 1: 01 -> Set bits = 1
Binary Representation of 2: 10 -> Set bits = 1
Binary Representation of 3: 11 -> Set bits = 2
Total set bits from 1 till 3 = 1 + 1 + 2 = 4

Input: n = 11
Output: 20

[Naive Approach] Counting Bits for each number

The idea is simple, we loop from 1 to n, count the set bits (1s) in binary form of each number and keep adding them to a running total. After processing all numbers, the total represents the number of set bits from 1 to n.


Output
20

Time Complexity: O(k*n), where k is the number of binary digits.
Auxiliary Space: O(1).

[Expected Approach] Using Pattern Based Approach - O(logn) Time and O(logn) Space

Instead of checking every number individually, we count how many times each bit position contributes as 1 in the entire range.

Since we know that for each bit in a binary number it follows a fixed periodic pattern as values increase. For the i-th bit (0-indexed), the pattern repeats for every period = 2(i+1)
Within each period:

  • The bit remains 0 (unset) for the first half of the period.
  • The bit remains 1 (set) for the second half of the period.

So the total times ith bit set is: 2i.
If we take a example of n = 11, Let’s observe binary numbers from 0 to 7

πŸ‘ 1bits

Whenever the i-th bit becomes set for the first time (that happens at the number 2i), all the numbers before it (from 0 to 2(i βˆ’ 1)) follow a fixed pattern: in each bit position, half of the numbers have that bit set and half of the numbers have that bit unset. So in this pattern of 2i numbers, each bit becomes set 2i/ 2 = 2(iβˆ’1) times.
And since there are i bit positions (from bit 0 to bit iβˆ’1), we multiply by i. So the total number of set bits becomes:

Total set bits = 2 i-1 * i

After calculating the set bits in the full pattern from 0 to (2i βˆ’ 1), we still have more numbers. The moment we cross 2i βˆ’ 1 and reach 2i, the i-th bit becomes set. And from 2i up to the number where that i-th bit remains set (say N). So the i-th bit contributes (N βˆ’ 2i + 1) set bits in this remaining part.
After solving the problem for the i-th set bit as the MSB, we then recursively solve the remaining part of the number and count the contribution of the next set bit.
For example:

πŸ‘ 420046984

Output
20
Comment
Article Tags:
Article Tags: