jayati

Longest Consecutive 1's

Oct 3rd, 2023
1,185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.00 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. /*  Function to calculate the longest consecutive ones
  12. *   N: given input to calculate the longest consecutive ones
  13. */
  14. class Solution
  15. {
  16.     public:
  17.     int maxConsecutiveOnes(int N)
  18.     {
  19.         int ans = 0;
  20.         int c = 0;
  21.  
  22.         while (N != 0)
  23.         {
  24.             if (N & 1)
  25.             {
  26.                 c++;
  27.                 ans = max(ans, c);
  28.             }
  29.             else
  30.             {
  31.                
  32.                 c = 0;
  33.             }
  34.  
  35.             N = N >> 1;
  36.         }
  37.  
  38.         ans = max(ans, c);
  39.  
  40.         return ans;
  41.     }
  42. };
  43.  
  44.  
  45. //{ Driver Code Starts.
  46.  
  47. // Driver Code
  48. int main() {
  49.     int t;
  50.     cin>>t;//testcases
  51.     while(t--)
  52.     {
  53.         int n;
  54.         cin>>n;//input n
  55.         Solution obj;
  56.         //calling maxConsecutiveOnes() function
  57.         cout<<obj.maxConsecutiveOnes(n)<<endl;
  58.     }
  59.     return 0;
  60. }
  61. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment