Skip to content

Commit

Permalink
Create Count total set bits
Browse files Browse the repository at this point in the history
  • Loading branch information
Udhay-Brahmi authored Dec 8, 2020
1 parent 60f95da commit 5d8383f
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions Count total set bits
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// { Driver Code Starts
//Initial Template for C++

#include<bits/stdc++.h>
using namespace std;


// } Driver Code Ends


//User function Template for C++

// Function to count set bits in the given number x
// n
int countSetBits(int n)
{
// Your logic here
if(n==0)return 0;
int x=log(n)/log(2);
return (x*(1<<(x-1)) + n+1-(1<<x) + countSetBits(n - (1<<x)));
}


// { Driver Code Starts.

// Driver code
int main()
{
int t;
cin>>t;// input testcases
while(t--) //while testcases exist
{
int n;
cin>>n; //input n

cout << countSetBits(n) << endl;// print the answer
}
return 0;
}
// } Driver Code Ends

0 comments on commit 5d8383f

Please sign in to comment.