-
Notifications
You must be signed in to change notification settings - Fork 5
/
GFG_LongestConsecutive1.cpp
61 lines (52 loc) · 1.16 KB
/
GFG_LongestConsecutive1.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
https://practice.geeksforgeeks.org/problems/longest-consecutive-1s-1587115620/1
Longest Consecutive 1's
https://binarysearch.com/problems/Longest-Consecutive-Run-of-1s-in-Binary
*/
//Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function Template for C++
/* Function to calculate the longest consecutive ones
* N: given input to calculate the longest consecutive ones
*/
class Solution
{
public:
int maxConsecutiveOnes(int N)
{
// code here
int len = 0, max_len=0;
while(N>0)
{
if(N&1 == 1)
len++;
else
{
if(max_len < len)
max_len = len;
len=0;
}
N>>=1;
}
if(max_len < len)
max_len = len;
return max_len;
}
};
// { Driver Code Starts.
// Driver Code
int main() {
int t;
cin>>t;//testcases
while(t--)
{
int n;
cin>>n;//input n
Solution obj;
//calling maxConsecutiveOnes() function
cout<<obj.maxConsecutiveOnes(n)<<endl;
}
return 0;
} // } Driver Code Ends