# Count total set bits in first N Natural Numbers (all numbers from 1 to N)

• Difficulty Level : Hard
• Last Updated : 26 Nov, 2022

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

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 = 6
Output: 9

Input: N = 7
Output: 12

Recommended Practice

Source: Amazon Interview Question

## Count total set bits by converting each number into its Binary Representation:

The idea is to convert each number from 1 till N into binary, and count the set bits in each number separately.

Follow the steps below to understand how:

• Traverse a loop from 1 to N
• For each integer in 1 to N:
• Convert the number to its binary representation
• Add the count of 1s in the binary representation to the answer.
• Return the total set bits count.

Below is the implementation of the above approach:

## C++

 // A simple program to count set bits// in all numbers from 1 to n.#include using namespace std; // A utility function to count set bits// in a number xunsigned int countSetBitsUtil(unsigned int x); // Returns count of set bits present in all// numbers from 1 to nunsigned int countSetBits(unsigned int n){    int bitCount = 0; // initialize the result     for (int i = 1; i <= n; i++)        bitCount += countSetBitsUtil(i);     return bitCount;} // A utility function to count set bits// in a number xunsigned int countSetBitsUtil(unsigned int x){    if (x <= 0)        return 0;    return (x % 2 == 0 ? 0 : 1) + countSetBitsUtil(x / 2);} // Driver program to test above functionsint main(){    int n = 4;    cout << "Total set bit count is " << countSetBits(n);    return 0;} // This code is contributed by shivanisinghss2110.

## C

 // A simple program to count set bits// in all numbers from 1 to n.#include  // A utility function to count set bits// in a number xunsigned int countSetBitsUtil(unsigned int x); // Returns count of set bits present in all// numbers from 1 to nunsigned int countSetBits(unsigned int n){    int bitCount = 0; // initialize the result     for (int i = 1; i <= n; i++)        bitCount += countSetBitsUtil(i);     return bitCount;} // A utility function to count set bits// in a number xunsigned int countSetBitsUtil(unsigned int x){    if (x <= 0)        return 0;    return (x % 2 == 0 ? 0 : 1) + countSetBitsUtil(x / 2);} // Driver program to test above functionsint main(){    int n = 4;    printf("Total set bit count is %d", countSetBits(n));    return 0;}

## Java

 // A simple program to count set bits// in all numbers from 1 to n. class GFG {     // Returns count of set bits present    //  in all numbers from 1 to n    static int countSetBits(int n)    {        // initialize the result        int bitCount = 0;         for (int i = 1; i <= n; i++)            bitCount += countSetBitsUtil(i);         return bitCount;    }     // A utility function to count set bits    // in a number x    static int countSetBitsUtil(int x)    {        if (x <= 0)            return 0;        return (x % 2 == 0 ? 0 : 1)            + countSetBitsUtil(x / 2);    }     // Driver program    public static void main(String[] args)    {        int n = 4;        System.out.print("Total set bit count is ");        System.out.print(countSetBits(n));    }} // This code is contributed by// Smitha Dinesh Semwal

## Python3

 # A simple program to count set bits# in all numbers from 1 to n. # Returns count of set bits present in all# numbers from 1 to n  def countSetBits(n):     # initialize the result    bitCount = 0     for i in range(1, n + 1):        bitCount += countSetBitsUtil(i)     return bitCount  # A utility function to count set bits# in a number xdef countSetBitsUtil(x):     if (x <= 0):        return 0    return (0 if int(x % 2) == 0 else 1) + countSetBitsUtil(int(x / 2))  # Driver programif __name__ == '__main__':    n = 4    print("Total set bit count is", countSetBits(n)) # This code is contributed by# Smitha Dinesh Semwal

## C#

 // A simple C# program to count set bits// in all numbers from 1 to n.using System; class GFG {    // Returns count of set bits present    // in all numbers from 1 to n    static int countSetBits(int n)    {        // initialize the result        int bitCount = 0;         for (int i = 1; i <= n; i++)            bitCount += countSetBitsUtil(i);         return bitCount;    }     // A utility function to count set bits    // in a number x    static int countSetBitsUtil(int x)    {        if (x <= 0)            return 0;        return (x % 2 == 0 ? 0 : 1)            + countSetBitsUtil(x / 2);    }     // Driver program    public static void Main()    {        int n = 4;        Console.Write("Total set bit count is ");        Console.Write(countSetBits(n));    }} // This code is contributed by Sam007



## Javascript

 // A simple program to count set bits// in all numbers from 1 to n.          // Returns count of set bits present    //  in all numbers from 1 to n    function countSetBits(n)    {        // initialize the result        let bitCount = 0;        for (let i = 1; i <= n; i++)        {            bitCount += countSetBitsUtil(i);        }        return bitCount;    }         // A utility function to count set bits    // in a number x    function countSetBitsUtil(x)    {        if (x <= 0)        {            return 0;        }        return (x % 2 == 0 ? 0 : 1) + countSetBitsUtil(Math.floor(x/2));    }         // Driver program    let n = 4;    console.log("Total set bit count is ");    console.log(countSetBits(n));         // This code is contributed by rag2127

Output

Total set bit count is 5

Time Complexity: O(N*log(N)), where N is the given integer and log(N) time is used for the binary conversion of the number.
Auxiliary Space: O(1).

Method 2 (Simple and efficient than Method 1)
If we observe bits from rightmost side at distance i than bits get inverted after 2^i position in vertical sequence.
for example n = 5;
0 = 0000
1 = 0001
2 = 0010
3 = 0011
4 = 0100
5 = 0101
Observe the right most bit (i = 0) the bits get flipped after (2^0 = 1)
Observe the 3rd rightmost bit (i = 2) the bits get flipped after (2^2 = 4)
So, We can count bits in vertical fashion such that at i’th right most position bits will be get flipped after 2^i iteration;

## C++

 #include using namespace std; // Function which counts set bits from 0 to nint countSetBits(int n){    int i = 0;     // ans store sum of set bits from 0 to n    int ans = 0;     // while n greater than equal to 2^i    while ((1 << i) <= n) {         // This k will get flipped after        // 2^i iterations        bool k = 0;         // change is iterator from 2^i to 1        int change = 1 << i;         // This will loop from 0 to n for        // every bit position        for (int j = 0; j <= n; j++) {             ans += k;             if (change == 1) {                k = !k; // When change = 1 flip the bit                change = 1 << i; // again set change to 2^i            }            else {                change--;            }        }         // increment the position        i++;    }     return ans;} // Main Functionint main(){    int n = 17;    cout << countSetBits(n) << endl;    return 0;}

## Java

 public class GFG {     // Function which counts set bits from 0 to n    static int countSetBits(int n)    {        int i = 0;         // ans store sum of set bits from 0 to n        int ans = 0;         // while n greater than equal to 2^i        while ((1 << i) <= n) {             // This k will get flipped after            // 2^i iterations            boolean k = false;             // change is iterator from 2^i to 1            int change = 1 << i;             // This will loop from 0 to n for            // every bit position            for (int j = 0; j <= n; j++) {                 if (k == true)                    ans += 1;                else                    ans += 0;                 if (change == 1) {                     // When change = 1 flip the bit                    k = !k;                     // again set change to 2^i                    change = 1 << i;                }                else {                    change--;                }            }             // increment the position            i++;        }         return ans;    }     // Driver program    public static void main(String[] args)    {        int n = 17;         System.out.println(countSetBits(n));    }} // This code is contributed by Sam007.

## Python3

 # Function which counts set bits from 0 to ndef countSetBits(n):    i = 0     # ans store sum of set bits from 0 to n    ans = 0     # while n greater than equal to 2^i    while ((1 << i) <= n):         # This k will get flipped after        # 2^i iterations        k = 0         # change is iterator from 2^i to 1        change = 1 << i         # This will loop from 0 to n for        # every bit position        for j in range(0, n+1):            ans += k             if change == 1:                 #  When change = 1 flip the bit                k = not k                 # again set change to 2^i                change = 1 << i             else:                change -= 1         # increment the position        i += 1     return ans  # Driver codeif __name__ == "__main__":     n = 17    print(countSetBits(n)) # This code is contributed by ANKITRAI1

## C#

 using System; class GFG {    static int countSetBits(int n)    {        int i = 0;         // ans store sum of set bits from 0 to n        int ans = 0;         // while n greater than equal to 2^i        while ((1 << i) <= n) {             // This k will get flipped after            // 2^i iterations            bool k = false;             // change is iterator from 2^i to 1            int change = 1 << i;             // This will loop from 0 to n for            // every bit position            for (int j = 0; j <= n; j++) {                 if (k == true)                    ans += 1;                else                    ans += 0;                 if (change == 1) {                     // When change = 1 flip the bit                    k = !k;                     // again set change to 2^i                    change = 1 << i;                }                else {                    change--;                }            }             // increment the position            i++;        }         return ans;    }     // Driver program    static void Main()    {        int n = 17;        Console.Write(countSetBits(n));    }} // This code is contributed by Sam007



## Javascript



Output

35

Time Complexity: O(k*n)
where k = number of bits to represent number n
k <= 64

Method 3 (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.

## C++

 #include  // A O(Logn) complexity program to count// set bits in all numbers from 1 to nusing namespace std; /* Returns position of leftmost set bit.The rightmost position is consideredas 0 */unsigned int getLeftmostBit(int n){    int m = 0;    while (n > 1) {        n = n >> 1;        m++;    }    return m;} /* Given the position of previous leftmostset bit in n (or an upper bound onleftmost position) returns the newposition 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); // Returns count of set bits present in// all numbers from 1 to nunsigned int countSetBits(unsigned int n){    // Get the position of leftmost set    // bit in n. This will be used as an    // upper bound for next set bit function    int m = getLeftmostBit(n);     // Use the position    return _countSetBits(n, m);} unsigned int _countSetBits(unsigned int n, int m){    // Base Case: if n is 0, then set bit    // count is 0    if (n == 0)        return 0;     /* get position of next leftmost set bit */    m = getNextLeftmostBit(n, m);     // If n is of the form 2^x-1, i.e., if n    // is like 1, 3, 7, 15, 31, .. etc,    // then we are done.    // Since positions are considered starting    // from 0, 1 is added to m    if (n == ((unsigned int)1 << (m + 1)) - 1)        return (unsigned int)(m + 1) * (1 << m);     // update n for next recursive call    n = n - (1 << m);    return (n + 1) + countSetBits(n) + m * (1 << (m - 1));} // Driver codeint main(){    int n = 17;    cout << "Total set bit count is " << countSetBits(n);    return 0;} // This code is contributed by rathbhupendra

## C

 // A O(Logn) complexity program to count// set bits in all numbers from 1 to n#include  /* 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); // Returns count of set bits present in// all numbers from 1 to nunsigned int countSetBits(unsigned int n){    // Get the position of leftmost set    // bit in n. This will be used as an    // upper bound for next set bit function    int m = getLeftmostBit(n);     // Use the position    return _countSetBits(n, m);} unsigned int _countSetBits(unsigned int n, int m){    // Base Case: if n is 0, then set bit    // count is 0    if (n == 0)        return 0;     /* get position of next leftmost set bit */    m = getNextLeftmostBit(n, m);     // If n is of the form 2^x-1, i.e., if n    // is like 1, 3, 7, 15, 31, .. etc,    // then we are done.    // Since positions are considered starting    // from 0, 1 is added to m    if (n == ((unsigned int)1 << (m + 1)) - 1)        return (unsigned int)(m + 1) * (1 << m);     // update n for next recursive call    n = n - (1 << m);    return (n + 1) + countSetBits(n) + m * (1 << (m - 1));} // Driver program to test above functionsint main(){    int n = 17;    printf("Total set bit count is %d", countSetBits(n));    return 0;}

## Java

 // Java A O(Logn) complexity program to count// set bits in all numbers from 1 to nimport java.io.*; class GFG {     /* Returns position of leftmost set bit.    The rightmost position is considered    as 0 */    static 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 */    static int getNextLeftmostBit(int n, int m)    {        int temp = 1 << m;        while (n < temp) {            temp = temp >> 1;            m--;        }        return m;    }     // The main recursive function used by countSetBits()    // Returns count of set bits present in    // all numbers from 1 to n     static int countSetBits(int n)    {        // Get the position of leftmost set        // bit in n. This will be used as an        // upper bound for next set bit function        int m = getLeftmostBit(n);         // Use the position        return countSetBits(n, m);    }     static int countSetBits(int n, int m)    {        // Base Case: if n is 0, then set bit        // count is 0        if (n == 0)            return 0;         /* get position of next leftmost set bit */        m = getNextLeftmostBit(n, m);         // If n is of the form 2^x-1, i.e., if n        // is like 1, 3, 7, 15, 31, .. etc,        // then we are done.        // Since positions are considered starting        // from 0, 1 is added to m        if (n == ((int)1 << (m + 1)) - 1)            return (int)(m + 1) * (1 << m);         // update n for next recursive call        n = n - (1 << m);        return (n + 1) + countSetBits(n)            + m * (1 << (m - 1));    }     // Driver code    public static void main(String[] args)    {         int n = 17;        System.out.println("Total set bit count is "                           + countSetBits(n));    }} // This code is contributed by ajit..

## Python3

 # A O(Logn) complexity program to count# set bits in all numbers from 1 to n """/* Returns position of leftmost set bit.The rightmost position is consideredas 0 */"""  def getLeftmostBit(n):     m = 0    while (n > 1):         n = n >> 1        m += 1     return m  """/* Given the position of previous leftmostset bit in n (or an upper bound onleftmost position) returns the newposition of leftmost set bit in n */"""  def getNextLeftmostBit(n, m):     temp = 1 << m    while (n < temp):        temp = temp >> 1        m -= 1     return m # The main recursive function used by countSetBits()# def _countSetBits(n, m) # Returns count of set bits present in# all numbers from 1 to n  def countSetBits(n):     # Get the position of leftmost set    # bit in n. This will be used as an    # upper bound for next set bit function    m = getLeftmostBit(n)     # Use the position    return _countSetBits(n, m)  def _countSetBits(n, m):     # Base Case: if n is 0, then set bit    # count is 0    if (n == 0):        return 0     # /* get position of next leftmost set bit */    m = getNextLeftmostBit(n, m)     # If n is of the form 2^x-1, i.e., if n    # is like 1, 3, 7, 15, 31, .. etc,    # then we are done.    # Since positions are considered starting    # from 0, 1 is added to m    if (n == (1 << (m + 1)) - 1):        return ((m + 1) * (1 << m))     # update n for next recursive call    n = n - (1 << m)    return (n + 1) + countSetBits(n) + m * (1 << (m - 1))  # Driver coden = 17print("Total set bit count is", countSetBits(n)) # This code is contributed by rathbhupendra

## C#

 // C# A O(Logn) complexity program to count// set bits in all numbers from 1 to nusing System; class GFG {     /* Returns position of leftmost set bit.    The rightmost position is considered    as 0 */    static 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 */    static int getNextLeftmostBit(int n, int m)    {        int temp = 1 << m;        while (n < temp) {            temp = temp >> 1;            m--;        }        return m;    }     // The main recursive function used by countSetBits()    // Returns count of set bits present in    // all numbers from 1 to n    static int countSetBits(int n)    {        // Get the position of leftmost set        // bit in n. This will be used as an        // upper bound for next set bit function        int m = getLeftmostBit(n);         // Use the position        return countSetBits(n, m);    }     static int countSetBits(int n, int m)    {        // Base Case: if n is 0,        // then set bit count is 0        if (n == 0)            return 0;         /* get position of next leftmost set bit */        m = getNextLeftmostBit(n, m);         // If n is of the form 2^x-1, i.e., if n        // is like 1, 3, 7, 15, 31, .. etc,        // then we are done.        // Since positions are considered starting        // from 0, 1 is added to m        if (n == ((int)1 << (m + 1)) - 1)            return (int)(m + 1) * (1 << m);         // update n for next recursive call        n = n - (1 << m);        return (n + 1) + countSetBits(n)            + m * (1 << (m - 1));    }     // Driver code    static public void Main()    {        int n = 17;        Console.Write("Total set bit count is "                      + countSetBits(n));    }} // This code is contributed by Tushil.

## Javascript



Output

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.
Thanks to agatsu and IC for suggesting this solution.
Here is another solution suggested by Piyush Kapoor.

A simple solution , using the fact that for the ith least significant bit, answer will be

(N/2^i)*2^(i-1)+ X

where

X = N%(2^i)-(2^(i-1)-1)

if

N%(2^i)>(2^(i-1)-1)

## C++

 int getSetBitsFromOneToN(int N){    int two = 2, ans = 0;    int n = N;    while (n) {        ans += (N / two) * (two >> 1);        if ((N & (two - 1)) > (two >> 1) - 1)            ans += (N & (two - 1)) - (two >> 1) + 1;        two <<= 1;        n >>= 1;    }    return ans;}

## Java

 static int getSetBitsFromOneToN(int N){    int two = 2, ans = 0;    int n = N;    while (n != 0) {        ans += (N / two) * (two >> 1);        if ((N & (two - 1)) > (two >> 1) - 1)            ans += (N & (two - 1)) - (two >> 1) + 1;        two <<= 1;        n >>= 1;    }    return ans;} // This code is contributed by divyeshrabadiya07.

## Python3

 def getSetBitsFromOneToN(N):    two = 2    ans = 0    n = N    while(n != 0)    {        ans += int(N / two) * (two >> 1)        if((N & (two - 1)) > (two >> 1) - 1):            ans += (N & (two - 1)) - (two >> 1) + 1        two <<= 1        n >>= 1    }    return ans # This code is contributed by avanitrachhadiya2155

## C#

 static int getSetBitsFromOneToN(int N){    int two = 2, ans = 0;    int n = N;    while (n != 0) {        ans += (N / two) * (two >> 1);        if ((N & (two - 1)) > (two >> 1) - 1)            ans += (N & (two - 1)) - (two >> 1) + 1;        two <<= 1;        n >>= 1;    }    return ans;} // This code is contributed by divyesh072019.

## Javascript



Method 4 (Recursive)

Approach:

For each number ‘n’, there will be a number a, where a<=n and a is perfect power of two, like 1,2,4,8…..

Let n = 11, now we can see that

Numbers till n, are:
0  -> 0000000
1  -> 0000001
2  -> 0000010
3  -> 0000011
4  -> 0000100
5  -> 0000101
6  -> 0000110
7  -> 0000111
8  -> 0001000
9  -> 0001001
10 -> 0001010
11 -> 0001011

Now we can see that, from 0 to pow(2,1)-1 = 1, we can pair elements top-most with bottom-most,
and count of set bit in a pair is 1

Similarly for pow(2,2)-1 = 4, pairs are:
00 and 11
01 and 10
here count of set bit in a pair is 2, so in both pairs is 4

Similarly we can see for 7, 15, ans soon.....

so we can generalise that,
count(x) = (x*pow(2,(x-1))),
here x is position of set bit of the largest power of 2 till n
for n = 8, x = 3
for n = 4, x = 2
for n = 5, x = 2

so now for n = 11,
we have added set bits count from 0 to 7 using count(x) = (x*pow(2,(x-1)))

for rest numbers 8 to 11, all will have a set bit at 3rd index, so we can add
count of rest numbers to our ans,
which can be calculated using 11 - 8 + 1 = (n-pow(2,x) + 1)

Now if notice that, after removing front bits from rest numbers, we get again number from 0 to some m
so we can recursively call our same function for next set of numbers,
by calling countSetBits(n - pow(2,x))
8  -> 1000  -> 000 -> 0
9  -> 1001  -> 001 -> 1
10 -> 1010  -> 010 -> 2
11 -> 1011  -> 011 -> 3

Code:

## C++

 #include using namespace std; int findLargestPower(int n){    int x = 0;    while ((1 << x) <= n)        x++;    return x - 1;} int countSetBits(int n){    if (n <= 1)        return n;    int x = findLargestPower(n);    return (x * pow(2, (x - 1))) + (n - pow(2, x) + 1)           + countSetBits(n - pow(2, x));} int main(){    int N = 17;    cout << countSetBits(N) << endl;    return 0;}

## Java

 import java.io.*;class GFG {    static int findLargestPower(int n)    {        int x = 0;        while ((1 << x) <= n)            x++;        return x - 1;    }     static int countSetBits(int n)    {        if (n <= 1)            return n;        int x = findLargestPower(n);        return (x * (int)Math.pow(2, (x - 1)))            + (n - (int)Math.pow(2, x) + 1)            + countSetBits(n - (int)Math.pow(2, x));    }     public static void main(String[] args)    {        int N = 17;        System.out.print(countSetBits(N));    }} // This code is contributed by shivanisinghss2110

## Python3

 def findLargestPower(n):     x = 0    while ((1 << x) <= n):        x += 1    return x - 1  def countSetBits(n):     if (n <= 1):        return n    x = findLargestPower(n)    return (x * pow(2, (x - 1))) + (n - pow(2, x) + 1) + countSetBits(n - pow(2, x))  N = 17print(countSetBits(N)) # This code is contributed by shivanisinghss2110

## C#

 using System;class GFG {    static int findLargestPower(int n)    {        int x = 0;        while ((1 << x) <= n)            x++;        return x - 1;    }     static int countSetBits(int n)    {        if (n <= 1)            return n;        int x = findLargestPower(n);        return (x * (int)Math.Pow(2, (x - 1)))            + (n - (int)Math.Pow(2, x) + 1)            + countSetBits(n - (int)Math.Pow(2, x));    }     public static void Main(string[] args)    {        int N = 17;        Console.Write(countSetBits(N));    }} // This code is contributed by shivanisinghss2110

## Javascript



Output

35

Time Complexity: O(LogN)

Method 5(Iterative)

Example:

0  -> 0000000     8  -> 001000      16  -> 010000    24 -> 011000

1  -> 0000001     9  -> 001001      17  -> 010001    25 -> 011001

2  -> 0000010    10  -> 001010     18 -> 010010     26 -> 011010

3  -> 0000011    11  -> 001011     19  -> 010010    27 -> 011011

4  -> 0000100    12  -> 001100     20  -> 010100    28 -> 011100

5  -> 0000101    13  -> 001101     21 -> 010101     29 -> 011101

6  -> 0000110    14  -> 001110     22 -> 010110     30 -> 011110

7  -> 0000111    15  -> 001111     23 -> 010111     31 -> 011111

Input: N = 4

Output: 5

Input: N = 17

Output: 35

Approach : Pattern recognition

Let ‘N’ be any arbitrary number and consider indexing from right to left(rightmost being 1); then  nearestPow = pow(2,i).

Now, when you write all numbers from 1 to N, you will observe the pattern mentioned below:

For every index i, there are exactly nearestPow/2 continuous elements that are unset followed by nearestPow/2 elements that are set.

Throughout the solution, i am going to use this concept.

You can clearly observe above concept in the above table.

The general formula that i came up with:

a. addRemaining = mod – (nearestPos/2) + 1 if mod >= nearestPow/2;

b. totalSetBitCount = totalRep*(nearestPow/2) + addRemaining

where totalRep -> total number of times the pattern repeats at index i

addRemaining -> total number of set bits left to be added after the pattern is exhausted

Eg:  let N = 17

leftMostSetIndex = 5 (Left most set bit index, considering 1 based indexing)

i = 1 => nearestPos = pow(2,1) = 2;   totalRep = (17+1)/2 = 9 (add 1 only for i=1)

mod = 17%2 = 1

addRemaining = 0 (only for base case)

totalSetBitCount = totalRep*(nearestPos/2) + addRemaining = 9*(2/2) + 0 = 9*1 + 0 = 9

i = 2 => nearestPos = pow(2, 2)=4;       totalRep = 17/4 = 4

mod = 17%4 = 1

mod(1) < (4/2) => 1 < 2 => addRemaining = 0

totalSetBitCount  = 9 + 4*(2) + 0 = 9 + 8 = 17

i = 3 => nearestPow = pow(2,3) = 8;    totalRep = 17/8 = 2

mod = 17%8 = 1

mod < 4 => addRemaining = 0

totalSetBitCount = 17 + 2*(4) + 0 = 17 + 8 + 0 = 25

i = 4 => nearestPow = pow(2, 4) = 16; totalRep = 17/16 = 1

mod = 17%16 = 1

mod < 8 => addRemaining = 0

totalSetBitCount  = 25 + 1*(8) + 0 = 25 + 8 + 0 = 33

We cannot simply operate on the next power(32) as 32>17. Also, as the first half bits will be 0s only, we need to find the distance of the given number(17) from the last power to directly get the number of 1s to be added

i = 5 => nearestPow = (2, 5) = 32 (base case 2)

lastPow = pow(2, 4) = 16

mod = 17%16 = 1

totalSetBit = 33 + (mod+1) = 33 + 1 + 1 = 35

Therefore, total num of set bits from 1 to 17 is 35

Try iterating with N = 30, for better understanding of the solution.

Solution

## C++

 #include #include  using namespace std; int GetLeftMostSetBit(int n){    int pos = 0;     while (n > 0) {        pos++;        n >>= 1;    }     return pos;} int TotalSetBitsFrom1ToN(int n){    int leftMostSetBitInd = GetLeftMostSetBit(n);     int totalRep, mod;    int nearestPow;    int totalSetBitCount = 0;    int addRemaining = 0;     int curr        = 0; // denotes the number of set bits at index i     // cout<<"leftMostSetBitInd: "< n) {            int lastPow = pow(2, i - 1);            mod = n % lastPow;            totalSetBitCount += mod + 1;        }        else {            if (i == 1 && n % 2 == 1) {                totalRep = (n + 1) / nearestPow;                mod = nearestPow % 2;                addRemaining = 0;            }            else {                totalRep = n / nearestPow;                mod = n % nearestPow;                 if (mod >= (nearestPow / 2)) {                    addRemaining                        = mod - (nearestPow / 2) + 1;                }                else {                    addRemaining = 0;                }            }             curr = totalRep * (nearestPow / 2)                   + addRemaining;            totalSetBitCount += curr;        }        // debug output at each iteration        // cout<

## Java

 import java.io.*;import java.util.*;class GFG {    static int GetLeftMostSetBit(int n)    {        int pos = 0;         while (n > 0) {            pos++;            n >>= 1;        }         return pos;    }     static int TotalSetBitsFrom1ToN(int n)    {        int leftMostSetBitInd = GetLeftMostSetBit(n);         int totalRep, mod;        int nearestPow;        int totalSetBitCount = 0;        int addRemaining = 0;         int curr = 0; // denotes the number of set bits at                      // index i         for (int i = 1; i <= leftMostSetBitInd; ++i) {            nearestPow = (int)Math.pow(2, i);            if (nearestPow > n) {                int lastPow = (int)Math.pow(2, i - 1);                mod = n % lastPow;                totalSetBitCount += mod + 1;            }            else {                if (i == 1 && n % 2 == 1) {                    totalRep = (n + 1) / nearestPow;                    mod = nearestPow % 2;                    addRemaining = 0;                }                else {                    totalRep = n / nearestPow;                    mod = n % nearestPow;                     if (mod >= (nearestPow / 2)) {                        addRemaining                            = mod - (nearestPow / 2) + 1;                    }                    else {                        addRemaining = 0;                    }                }                 curr = totalRep * (nearestPow / 2)                       + addRemaining;                totalSetBitCount += curr;            }        }         return totalSetBitCount;    }     public static void main(String[] args)    {        System.out.println(TotalSetBitsFrom1ToN(4));        System.out.println(TotalSetBitsFrom1ToN(17));        System.out.println(TotalSetBitsFrom1ToN(30));    }} // This code is contributed by vikaschhonkar1// By: Vikas Chhonkar

## Python3

 def get_left_most_set_bit(n):    left_most_set_bit_indx = 0     while n > 0:        left_most_set_bit_indx += 1        n >>= 1     return left_most_set_bit_indx  def total_set_bits_from_1_to_n(n):    left_most_set_bit_indx = get_left_most_set_bit(n)    total_rep = 0    mod = 0    nearest_pow = 0    total_set_bit_count = 0    add_remaining = 0    curr = 0  # denotes the number of set bits at index i     for i in range(1, left_most_set_bit_indx + 1):        nearest_pow = pow(2, i)        if nearest_pow > n:            last_pow = pow(2, i-1)            mod = n % last_pow            total_set_bit_count += mod + 1         else:            if i == 1 and n % 2 == 1:                total_rep = (n + 1) / nearest_pow                mod = nearest_pow % 2                add_remaining = 0            else:                total_rep = int(n / nearest_pow)                mod = n % nearest_pow                add_remaining = int(                    mod - (nearest_pow / 2) + 1) if mod >= nearest_pow / 2 else 0             curr = int(total_rep * (nearest_pow / 2) + add_remaining)            total_set_bit_count += curr     return total_set_bit_count  # Driver codeif __name__ == "__main__":    print(total_set_bits_from_1_to_n(4))    print(total_set_bits_from_1_to_n(17))    print(total_set_bits_from_1_to_n(30))     # This code is contributed by tssovi.

## C#

 // C# program for the above approachusing System; public class GFG {     static int GetLeftMostSetBit(int n)    {        int pos = 0;         while (n > 0) {            pos++;            n >>= 1;        }         return pos;    }     static int TotalSetBitsFrom1ToN(int n)    {        int leftMostSetBitInd = GetLeftMostSetBit(n);         int totalRep, mod;        int nearestPow;        int totalSetBitCount = 0;        int addRemaining = 0;         int curr = 0; // denotes the number of set bits at                      // index i         for (int i = 1; i <= leftMostSetBitInd; ++i) {            nearestPow = (int)Math.Pow(2, i);            if (nearestPow > n) {                int lastPow = (int)Math.Pow(2, i - 1);                mod = n % lastPow;                totalSetBitCount += mod + 1;            }            else {                if (i == 1 && n % 2 == 1) {                    totalRep = (n + 1) / nearestPow;                    mod = nearestPow % 2;                    addRemaining = 0;                }                else {                    totalRep = n / nearestPow;                    mod = n % nearestPow;                     if (mod >= (nearestPow / 2)) {                        addRemaining                            = mod - (nearestPow / 2) + 1;                    }                    else {                        addRemaining = 0;                    }                }                 curr = totalRep * (nearestPow / 2)                       + addRemaining;                totalSetBitCount += curr;            }        }         return totalSetBitCount;    }     // Driver Code    public static void Main(String[] args)    {         Console.WriteLine(TotalSetBitsFrom1ToN(4));        Console.WriteLine(TotalSetBitsFrom1ToN(17));        Console.WriteLine(TotalSetBitsFrom1ToN(30));    }} // This code is contributed by code_hunt.

## Javascript



Output

5
35
75

Time Complexity: O(log(n))

My Personal Notes arrow_drop_up