Given a positive integer n, count the total number of set bits in binary representation of all numbers from 1 to n.

Examples:

Input: n = 3
Output:  4

Input: n = 6
Output: 9

Input: n = 7
Output: 12

Input: n = 8
Output: 13

We strongly recommend that you click here and practice it, before moving on to the solution.

[ad type=”banner”]

Method 1 (Simple)
A simple solution is to run a loop from 1 to n and sum the count of set bits in all numbers from 1 to n.

[pastacode lang=”c” manual=”%2F%2F%20A%20simple%20program%20to%20count%20set%20bits%20in%20all%20numbers%20from%201%20to%20n.%0A%23include%20%3Cstdio.h%3E%0A%20%0A%2F%2F%20A%20utility%20function%20to%20count%20set%20bits%20in%20a%20number%20x%0Aunsigned%20int%20countSetBitsUtil(unsigned%20int%20x)%3B%0A%20%0A%2F%2F%20Returns%20count%20of%20set%20bits%20present%20in%20all%20numbers%20from%201%20to%20n%0Aunsigned%20int%20countSetBits(unsigned%20int%20n)%0A%7B%0A%20%20%20%20int%20bitCount%20%3D%200%3B%20%2F%2F%20initialize%20the%20result%0A%20%0A%20%20%20%20for(int%20i%20%3D%201%3B%20i%20%3C%3D%20n%3B%20i%2B%2B)%0A%20%20%20%20%20%20%20bitCount%20%2B%3D%20countSetBitsUtil(i)%3B%0A%20%0A%20%20%20%20return%20bitCount%3B%0A%7D%0A%20%0A%2F%2F%20A%20utility%20function%20to%20count%20set%20bits%20in%20a%20number%20x%0Aunsigned%20int%20countSetBitsUtil(unsigned%20int%20x)%0A%7B%0A%20%20%20%20if%20(x%20%3C%3D%200)%0A%20%20%20%20%20%20%20%20return%200%3B%0A%20%20%20%20return%20(x%20%252%20%3D%3D%200%3F%200%3A%201)%20%2B%20countSetBitsUtil%20(x%2F2)%3B%0A%7D%0A%20%0A%2F%2F%20Driver%20program%20to%20test%20above%20functions%0Aint%20main()%0A%7B%0A%20%20%20int%20n%20%3D%204%3B%0A%20%20%20printf%20(%22Total%20set%20bit%20count%20is%20%25d%22%2C%20countSetBits(n))%3B%0A%20%20%20return%200%3B%0A%7D” message=”c” highlight=”” provider=”manual”/]

Output:

Total set bit count is 5

Time Complexity: O(nLogn)

[ad type=”banner”]

Method 2 (Tricky)
If the input number is of the form 2^b -1 e.g., 1,3,7,15.. etc, the number of set bits is b * 2^(b-1). This is because for all the numbers 0 to (2^b)-1, if you complement and flip the list you end up with the same list (half the bits are on, half off).

If the number does not have all set bits, then some position m is the position of leftmost set bit. The number of set bits in that position is n – (1 << m) + 1. The remaining set bits are in two parts: 1) The bits in the (m-1) positions down to the point where the leftmost bit becomes 0, and 2) The 2^(m-1) numbers below that point, which is the closed form above. An easy way to look at it is to consider the number 6:

0|0 0
0|0 1
0|1 0
0|1 1
-|–
1|0 0
1|0 1
1|1 0
The leftmost set bit is in position 2 (positions are considered starting from 0). If we mask that off what remains is 2 (the “1 0” in the right part of the last row.) So the number of bits in the 2nd position (the lower left box) is 3 (that is, 2 + 1). The set bits from 0-3 (the upper right box above) is 2*2^(2-1) = 4. The box in the lower right is the remaining bits we haven’t yet counted, and is the number of set bits for all the numbers up to 2 (the value of the last entry in the lower right box) which can be figured recursively.

// A O(Logn) complexity program to count set bits in all numbers from 1 to n
#include <stdio.h>
/* Returns position of leftmost set bit. The rightmost
   position is considered as 0 */
unsigned int getLeftmostBit (int n)
{
   int m = 0;
   while (n  > 1)
   {
      n = n >> 1;
      m++;
   }
   return m;
}
/* Given the position of previous leftmost set bit in n (or an upper
   bound on leftmost position) returns the new position of leftmost
   set bit in n  */
unsigned int getNextLeftmostBit (int n, int m)
{
   unsigned int temp = 1 << m;
   while (n  < temp)
   {
      temp = temp >> 1;
      m--;
   }
   return m;
}
// The main recursive function used by countSetBits()
unsigned int _countSetBits(unsigned int n, int m);
[pastacode lang=”c” manual=”%2F%2F%20Returns%20count%20of%20set%20bits%20present%20in%20all%20numbers%20from%201%20to%20n%0Aunsigned%20int%20countSetBits(unsigned%20int%20n)%0A%7B%0A%20%20%20%2F%2F%20Get%20the%20position%20of%20leftmost%20set%20bit%20in%20n.%20This%20will%20be%0A%20%20%20%2F%2F%20used%20as%20an%20upper%20bound%20for%20next%20set%20bit%20function%0A%20%20%20int%20m%20%3D%20getLeftmostBit%20(n)%3B%0A%20%0A%20%20%20%2F%2F%20Use%20the%20position%0A%20%20%20return%20_countSetBits%20(n%2C%20m)%3B%0A%7D%0A%20%0Aunsigned%20int%20_countSetBits(unsigned%20int%20n%2C%20int%20m)%0A%7B%0A%20%20%20%20%2F%2F%20Base%20Case%3A%20if%20n%20is%200%2C%20then%20set%20bit%20count%20is%200%0A%20%20%20%20if%20(n%20%3D%3D%200)%0A%20%20%20%20%20%20%20return%200%3B%0A%20%0A%20%20%20%20%2F*%20get%20position%20of%20next%20leftmost%20set%20bit%20*%2F%0A%20%20%20%20m%20%3D%20getNextLeftmostBit(n%2C%20m)%3B%0A%20%0A%20%20%20%20%2F%2F%20If%20n%20is%20of%20the%20form%202%5Ex-1%2C%20i.e.%2C%20if%20n%20is%20like%201%2C%203%2C%207%2C%2015%2C%2031%2C..%20etc%2C%20%0A%20%20%20%20%2F%2F%20then%20we%20are%20done.%20%0A%20%20%20%20%2F%2F%20Since%20positions%20are%20considered%20starting%20from%200%2C%201%20is%20added%20to%20m%0A%20%20%20%20if%20(n%20%3D%3D%20((unsigned%20int)1%3C%3C(m%2B1))-1)%0A%20%20%20%20%20%20%20%20return%20(unsigned%20int)(m%2B1)*(1%3C%3Cm)%3B%0A%20%0A%20%20%20%20%2F%2F%20update%20n%20for%20next%20recursive%20call%0A%20%20%20%20n%20%3D%20n%20-%20(1%3C%3Cm)%3B%0A%20%20%20%20return%20(n%2B1)%20%2B%20countSetBits(n)%20%2B%20m*(1%3C%3C(m-1))%3B%0A%7D” message=”c” highlight=”” provider=”manual”/]
// Driver program to test above functions
int main()
{
   int n = 17;
   printf ("Total set bit count is %d", countSetBits(n));
   return 0;
}
Total set bit count is 35

Time Complexity: O(Logn). From the first look at the implementation, time complexity looks more. But if we take a closer look, statements inside while loop of getNextLeftmostBit() are executed for all 0 bits in n. And the number of times recursion is executed is less than or equal to set bits in n. In other words, if the control goes inside while loop of getNextLeftmostBit(), then it skips those many bits in recursion.

[ad type=”banner”]