Given a number n, The task is to find the length of the longest consecutive 1s series in its binary representation.
Examples :
Input: n = 14
Output: 3
Explanation: The binary representation of 14 is 1110.Input: n = 222
Output: 4
Explanation: The binary representation of 222 is 11011110.
Table of Content
[Naive Approach] Iterative Time O(1) and Space O(1)
#include <iostream>
using namespace std;
int maxConsecutiveOne(int n ){
int count = 0 ;
int maxi = 0 ;
// traverse and check if bit set increment the count
for (int i = 0 ; i < 32 ; i++){
if (n & (1 << i)){
count++;
} else {
maxi = max (maxi , count);
count = 0 ;
}
}
return maxi;
}
int main() {
int n = 14 ;
cout << maxConsecutiveOne(n) <<'\n';
return 0;
}
public class GFG {
static int maxConsecutiveOne(int n) {
int count = 0;
int maxi = 0;
// traverse and check if bit set increment the count
for (int i = 0; i < 32; i++) {
if ((n & (1 << i)) != 0) {
count++;
} else {
maxi = Math.max(maxi, count);
count = 0;
}
}
return maxi;
}
public static void main(String[] args) {
int n = 14;
System.out.println(maxConsecutiveOne(n));
}
}
def maxConsecutiveOne(n):
count = 0
maxi = 0
# traverse and check if bit set increment the count
for i in range(32):
if n & (1 << i):
count += 1
else:
maxi = max(maxi, count)
count = 0
return maxi
if __name__ == "__main__":
n = 14
print(maxConsecutiveOne(n))
using System;
class GFG
{
static int MaxConsecutiveOne(int n)
{
int count = 0;
int maxi = 0;
// traverse and check if bit set increment the count
for (int i = 0; i < 32; i++)
{
if ((n & (1 << i)) != 0)
{
count++;
}
else
{
maxi = Math.Max(maxi, count);
count = 0;
}
}
return maxi;
}
static void Main()
{
int n = 14;
Console.WriteLine(MaxConsecutiveOne(n));
}
}
function maxConsecutiveOne(n) {
let count = 0;
let maxi = 0;
// traverse and check if bit set increment the count
for (let i = 0; i < 32; i++) {
if (n & (1 << i)) {
count++;
} else {
maxi = Math.max(maxi, count);
count = 0;
}
}
return maxi;
}
// Driver code
let n = 14;
console.log(maxConsecutiveOne(n));
Output
3
[Efficient Approach] Using Bit Manipulation O(1) Time and O(1) Space
The idea is based on the concept that the AND of bit sequence with a left shifted by 1 version of itself effectively removes the trailing 1 from every sequence of consecutive 1s.
So the operation n = (n & (n << 1)) reduces length of every sequence of 1s by one in binary representation of n. If we keep doing this operation in a loop, we end up with n = 0. The number of iterations required to reach 0 is actually length of the longest consecutive sequence of 1s.
Illustration:
Follow the below steps to implement the above approach:
- Create a variable count initialized with value 0.
- Run a while loop till n is not 0.
- In each iteration perform the operation n = (n & (n << 1))
- Increment count by one.
- Return count
#include<iostream>
using namespace std;
int maxConsecutiveOnes(int x)
{
// Initialize result
int count = 0;
// Count the number of iterations to
// reach x = 0.
while (x!=0)
{
// This operation reduces length
// of every sequence of 1s by one.
x = (x & (x << 1));
count++;
}
return count;
}
int main()
{
// Function Call
cout << maxConsecutiveOnes(14) << endl;
return 0;
}
class GFG
{
private static int maxConsecutiveOnes(int x)
{
// Initialize result
int count = 0;
// Count the number of iterations to
// reach x = 0.
while (x!=0)
{
// This operation reduces length
// of every sequence of 1s by one.
x = (x & (x << 1));
count++;
}
return count;
}
public static void main(String strings[])
{
System.out.println(maxConsecutiveOnes(14));
}
}
def maxConsecutiveOnes(x):
# Initialize result
count = 0
# Count the number of iterations to
# reach x = 0.
while (x!=0):
# This operation reduces length
# of every sequence of 1s by one.
x = (x & (x << 1))
count=count+1
return count
if __name__ == "__main__":
print(maxConsecutiveOnes(14))
# by Anant Agarwal.
using System;
class GFG {
// Function to find length of the
// longest consecutive 1s in binary
// representation of a number
private static int maxConsecutiveOnes(int x)
{
// Initialize result
int count = 0;
// Count the number of iterations
// to reach x = 0.
while (x != 0)
{
// This operation reduces length
// of every sequence of 1s by one.
x = (x & (x << 1));
count++;
}
return count;
}
// Driver code
public static void Main()
{
Console.WriteLine(maxConsecutiveOnes(14));
}
}
// This code is contributed by Nitin Mittal.
function maxConsecutiveOnes(x) {
// Initialize result
let count = 0;
// Count the number of iterations to reach x = 0
while (x !== 0) {
// This operation reduces length of
// every sequence of 1s by one
x = (x & (x << 1));
count++;
}
return count;
}
// Driver code
console.log(maxConsecutiveOnes(14));
<?php
// PHP program to find length
function maxConsecutiveOnes($n)
{
// Initialize result
$count = 0;
// Count the number of
// iterations to reach x = 0.
while ($n != 0)
{
// This operation reduces
// length of every sequence
// of 1s by one.
$n = ($n & ($n << 1));
$count++;
}
return $count;
}
echo maxConsecutiveOnes(14), "\n";
?>
Output
3
Time Complexity: O(1)
Auxiliary Space: O(1)
[Another Approach] Using String Conversion
We initialize two variables, max_len and cur_len, to 0. Then, we iterate through each bit of the integer n. If the least significant bit (LSB) is 1, we increment cur_len to count the current run of consecutive 1s. If the LSB is 0, it breaks the current sequence, so we update max_len if cur_len is greater and reset cur_len to 0. After checking each bit, we right shift n by 1 to move to the next bit. Finally, after the loop ends, we perform a last update of max_len if the final cur_len is greater, and return max_len as the length of the longest sequence of consecutive 1s.
#include <iostream>
#include <bitset>
#include <string>
using namespace std;
int maxConsecutiveOnes(int n){
string binary = bitset<32>(n).to_string();
int count = 0;
int maxCount = 0;
// Loop through the binary string to
// find the longest consecutive 1s
for (int i = 0; i < binary.size(); i++) {
if (binary[i] == '1') {
count++;
if (count > maxCount) {
maxCount = count;
}
} else {
count = 0;
}
}
// Print the result
return maxCount ;
}
int main() {
int n = 14;
cout << maxConsecutiveOnes(n) <<'\n';
return 0;
}
import java.util.*;
public class Main {
static int maxConsecutiveOnes(int n) {
String binary = String.format("%32s", Integer.toBinaryString(n)).replace(' ', '0');
int count = 0;
int maxCount = 0;
// Loop through the binary string to
// find the longest consecutive 1s
for (int i = 0; i < binary.length(); i++) {
if (binary.charAt(i) == '1') {
count++;
if (count > maxCount) {
maxCount = count;
}
} else {
count = 0;
}
}
// Return the result
return maxCount;
}
public static void main(String[] args) {
int n = 14;
System.out.println(maxConsecutiveOnes(n));
}
}
def maxConsecutiveOnes(n):
binary = format(n, '032b')
count = 0
maxCount = 0
# Loop through the binary string to
# find the longest consecutive 1s
for bit in binary:
if bit == '1':
count += 1
if count > maxCount:
maxCount = count
else:
count = 0
# Return the result
return maxCount
if __name__ == "__main__":
n = 14
print(maxConsecutiveOnes(n))
using System;
class GFG
{
static int MaxConsecutiveOnes(int n)
{
string binary = Convert.ToString(n, 2).PadLeft(32, '0');
int count = 0;
int maxCount = 0;
// Loop through the binary string to
// find the longest consecutive 1s
foreach (char bit in binary)
{
if (bit == '1')
{
count++;
if (count > maxCount)
maxCount = count;
}
else
{
count = 0;
}
}
// Return the result
return maxCount;
}
static void Main()
{
int n = 14;
Console.WriteLine(MaxConsecutiveOnes(n));
}
}
function maxConsecutiveOnes(n) {
let binary = n.toString(2).padStart(32, '0');
let count = 0;
let maxCount = 0;
// Loop through the binary string to
// find the longest consecutive 1s
for (let i = 0; i < binary.length; i++) {
if (binary[i] === '1') {
count++;
if (count > maxCount) {
maxCount = count;
}
} else {
count = 0;
}
}
// Return the result
return maxCount;
}
// Driver code
let n = 14;
console.log(maxConsecutiveOnes(n));
Output
3