![]() |
VOOZH | about |
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 = 4Input: n = 11
Output: 20
Table of Content
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.
20
Time Complexity: O(k*n), where k is the number of binary digits.
Auxiliary Space: O(1).
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:
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
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:
20