forked from mandliya/algorithms_and_data_structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
60f95da
commit 5d8383f
Showing
1 changed file
with
40 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |