Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //{ Driver Code Starts
- //Initial Template for C++
- #include<bits/stdc++.h>
- using namespace std;
- // } Driver Code Ends
- //User function Template for C++
- class Solution{
- public:
- // n: input to count the number of set bits
- //Function to return sum of count of set bits in the integers from 1 to n.
- int findlargest(int num)
- {
- int x=0;
- while(1<<x <= num)
- {
- x++;
- }
- return x-1;
- }
- int countSetBits(int n)
- {
- if(n==0)
- {
- return 0;
- }
- int x=findlargest(n);
- int counttillx=(1<<(x-1))*x;
- int countafterx=(n-(1<<x))+1;
- int rest= (n-(1<<x));
- int ans=counttillx+countafterx+countSetBits(rest);
- return ans;
- }
- };
- //{ Driver Code Starts.
- // Driver code
- int main()
- {
- int t;
- cin>>t;// input testcases
- while(t--) //while testcases exist
- {
- int n;
- cin>>n; //input n
- Solution ob;
- cout << ob.countSetBits(n) << endl;// print the answer
- }
- return 0;
- }
- // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment