jayati

Count total set bits

Oct 3rd, 2023
990
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.10 KB | None | 0 0
  1. //{ Driver Code Starts
  2. //Initial Template for C++
  3.  
  4. #include<bits/stdc++.h>
  5. using namespace std;
  6.  
  7.  
  8. // } Driver Code Ends
  9. //User function Template for C++
  10.  
  11. class Solution{
  12.     public:
  13.     // n: input to count the number of set bits
  14.     //Function to return sum of count of set bits in the integers from 1 to n.
  15.     int findlargest(int num)
  16.     {
  17.         int x=0;
  18.         while(1<<x <= num)
  19.         {
  20.             x++;
  21.         }
  22.         return x-1;
  23.     }
  24.     int countSetBits(int n)
  25.     {
  26.         if(n==0)
  27.         {
  28.             return 0;
  29.         }
  30.         int x=findlargest(n);
  31.         int counttillx=(1<<(x-1))*x;
  32.         int countafterx=(n-(1<<x))+1;
  33.         int rest= (n-(1<<x));
  34.         int ans=counttillx+countafterx+countSetBits(rest);
  35.         return ans;
  36.     }
  37. };
  38.  
  39.  
  40. //{ Driver Code Starts.
  41.  
  42. // Driver code
  43. int main()
  44. {
  45.      int t;
  46.      cin>>t;// input testcases
  47.      while(t--) //while testcases exist
  48.      {
  49.            int n;
  50.            cin>>n; //input n
  51.            Solution ob;
  52.            cout << ob.countSetBits(n) << endl;// print the answer
  53.       }
  54.       return 0;
  55. }
  56.  
  57. // } Driver Code Ends
Tags: Imp
Advertisement
Add Comment
Please, Sign In to add comment