Count total set bits | Practice | GeeksforGeeks

You are given a number N. Find the total count of set bits for all numbers from 1 to N(both inclusive).

Example 1:
Input: N = 4
Output: 5
Explanation:
For numbers from 1 to 4.
For 1: 0 0 1 = 1 set bits
For 2: 0 1 0 = 1 set bits
For 3: 0 1 1 = 2 set bits
For 4: 1 0 0 = 1 set bits
Therefore, the total set bits is 5.

Example 2:
Input: N = 17
Output: 35
Explanation: From numbers 1 to 17(both inclusive), 
the total number of set bits is 35.

Your Task: The task is to complete the function countSetBits() that takes n as a parameter and returns the count of all bits.

Expected Time Complexity: O(log N).
Expected Auxiliary Space: O(1).

Constraints:
1 ≤ N ≤ 108
0
atulharsh274Premium3 days ago
//c++ solution
int largestPowerOfTwo(int n){     int x=0;     while((1<<x) <= n){         x++;     }     return x-1;}
int countSetBits(int n){   int x = largestPowerOfTwo(n);   if(n==0)     return 0;      else return (1<<(x-1))*x + (n- (1<<x) +1 ) + countSetBits( n- (1<<x));} 
0
amarrajsmart1971 week ago
C++ Solution>> Using Recursive call.
 int powerless(int n)   {       int i=0;       while(pow(2,i)<=n)       {           i++;       }       return (i-1);   }   int countSetBits(int n)   {       // Your logic here       if(n<=1)       return n;       int x=powerless(n);       return ((pow(2,x-1)*x)+(n-pow(2,x)+1)+countSetBits(n-pow(2,x)));          }
0
khandelwalkusum2361 week ago
Whats is wrong in this , only 3500 something testcase passing
 
public static int countSetBits(int n){          // Your code here       int count=0;       if(n==0){           return 0;       }       for(int i=1;i<=n;i++){           int k=i;           while(k>0){               k=k&(k-1);               count++;           }       }       return count;          }
+3
dmmathpal7772 weeks ago
        // Without Recursion
        int set_n = 0;        for (int i = 2; i <= n * 2; i = i * 2) {            set_n = set_n + ((n / i) * (i / 2));            if (n % i != 0)               if (n % i >= i/2)                   set_n = set_n + ((n % i) - i/2 + 1);        }       return set_n;
+1
vermaashitiit3 weeks ago
200 IQ solution!!
 if(n==0) return 0; if(n%2==0) return countSetBits(n/2)+countSetBits((n-1)/2)+n/2; if(n%2!=0) return 2*countSetBits((n-1)/2)+(n-1)/2+1;
+1
adityagagtiwari4 weeks ago
Easy solution 
class Solution{      //Function to return sum of count of set bits in the integers from 1 to n.   public static int countSetBits(int n){          if(n==0)       return 0;       //formula for calculation       //Solve(n)= pow(2,x-1)*x+(n-pow(2,x)+1)+Solve(n-pow(2,x))       //where x is the highest power of 2 such that pow(2,x)<=n              //here we are calculating the power of 2 i.e. x       int x = 0;        while((1<<x)<=n)       {            x++;       }       // 1<<x represents 2 raised to power of x       //here reducing x to cover for that extra power raised        x = x-1;              int bitsuptox = (1<<(x-1))*x;       int setmsbofrest = n -(1<<x)+1;       int rest = n-(1<<x);       return bitsuptox + setmsbofrest + countSetBits(rest);   }}
0
milindprajapatmst191 month ago
0.2/1.3
Time Complexity: O(log(n))
Space Complexity: O(1)

class Solution{
    public:
    int countSetBits(int n) {
        int bit = n, k = 2, result = 0;
        n++;
        while (bit) {
            int p = n / k;
            result += p * (k >> 1);
            result += max(0, (n % k) - (k >> 1));
            k <<= 1;
            bit >>= 1;
        }
        return result;
    }
};
0
lawbindpandey01w1 month ago
C++ Solution where time complexity : theta(log n) and auxilary space complexity : theta(1);
 
 
int countSetBits(int n)   {       // Your logic here       int nob = 0;       int temp = n;       while((temp = (temp >> 1))) nob++;       //cout << nob+1 << "\n";               int count = 0;       for(int i = 1; i <= int(pow(2,nob)); i *= 2){                      count += n / (i * 2) * i;           int tc = (n%(i*2)) -i + 1;           if(tc > 0) count += tc;       }              return count;   }
+1
siddharth191111 month ago
simple O(log n) recursive solution
int countSetBits(int n)
    {
        // Your logic here
        if(n <= 1)
            return n;
        int x = log2(n);
        int v = pow(2,x-1);
        return v * x + (n - v * 2 + 1) + countSetBits(n-v*2);
    }
+1
himanshukug19cs1 month ago
    if(n==0)          return 0;     int x=lpowo2till(n);     return x*(1<<(x-1))+(n-(1<<x)+1)+countSetBits(n-(1<<x));   }    static int lpowo2till(int n){        int x=0;        while((1<<x)<=n){            x++;        }        return x-1;    }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.