Length of the Longest Consecutive 1s in Binary Representation
Last Updated :
01 Sep, 2023
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.
Naive Approach: Below is the idea to solve the problem
Traverse the bits of binary representation of N and keep a track of the number of consecutive set bits, and the maximum length of consecutive 1s found so far.
Time Complexity: O(X), Here X is the length of binary representation of N.
Auxiliary Space: O(1)
Find the length of the longest consecutive 1s series using Bit Magic:
Below is the idea to solve the problem:
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:
11101111 (x)
& 11011110 (x << 1)
---------------------------
11001110 (x & (x << 1))
^ ^
| |
Trailing 1 removed
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
Below is the Implementation of above approach:
C++
// C++ program to find length of the longest
// consecutive 1s in binary representation of
// a number.
#include<bits/stdc++.h>
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;
}
// Driver code
int main()
{
// Function Call
cout << maxConsecutiveOnes(14) << endl;
cout << maxConsecutiveOnes(222) << endl;
return 0;
}
Java
// Java program to find length of the longest
// consecutive 1s in binary representation of
// a number.
class MaxConsecutiveOnes
{
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(String strings[])
{
System.out.println(maxConsecutiveOnes(14));
System.out.println(maxConsecutiveOnes(222));
}
}
Python3
# Python program to find
# length of the longest
# consecutive 1s in
# binary representation of
# a number.
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
# Driver code
print(maxConsecutiveOnes(14))
print(maxConsecutiveOnes(222))
# This code is contributed
# by Anant Agarwal.
C#
// C# program to find length of the
// longest consecutive 1s in binary
// representation of a number.
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));
Console.Write(maxConsecutiveOnes(222));
}
}
// This code is contributed by Nitin Mittal.
JavaScript
<script>
// Javascript program to find length
// of the longest consecutive 1s in
// binary representation of a number.
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
document.write(maxConsecutiveOnes(14) + "<br/>");
document.write(maxConsecutiveOnes(222));
// This code is contributed by code_hunt
</script>
PHP
<?php
// PHP program to find length
// of the longest consecutive
// 1s in binary representation of
// a number.
function 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++;
}
return $count;
}
// Driver code
echo maxConsecutiveOnes(14), "\n";
echo maxConsecutiveOnes(222), "\n";
// This code is contributed by Ajit
?>
Time Complexity: O(log X), Here X is the length of binary representation of N
Auxiliary Space: O(1)
Approach 2: Using String Conversion
Here's a brief explanation of the algorithm:
We start by initializing max_len and cur_len to 0. Then, we iterate through the bits of the given integer n. If we encounter a 1 bit, we increment cur_len. If we encounter a 0 bit, we update max_len if cur_len is greater than max_len, and reset cur_len to 0. This is because a 0 bit breaks the current run of consecutive 1s. Finally, we return max_len.
- Initialize a variable max_len to 0 to store the length of the longest consecutive 1s found so far.
- Initialize a variable cur_len to 0 to store the length of the current consecutive 1s.
- While the integer n is not equal to 0, perform the following steps:
- If the least significant bit (LSB) of n is 1, increment cur_len.
- If the LSB of n is 0, update max_len if cur_len is greater than max_len, and reset cur_len to.
- Right shift n by 1 bit.
- If cur_len is greater than max_len, update max_len.
- Return max_len.
C++
// C++ program to find the length of the longest
// consecutive 1s in binary representation of
// a number.
#include <iostream>
#include <bitset>
#include <string>
using namespace std;
int main() {
int num = 222;
// Convert the integer to its binary representation as a string
string binary = bitset<32>(num).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
cout << "The length of the longest consecutive 1s in the binary representation is: " << maxCount << endl;
return 0;
}
Java
// Java program to find the length of the longest
// consecutive 1s in binary representation of
// a number.
import java.util.Arrays;
public class LongestConsecutiveOnes {
public static void main(String[] args) {
int num = 222;
// Convert the integer to its binary representation as a string
String binary = String.format("%32s", Integer.toBinaryString(num)).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;
}
}
// Print the result
System.out.println("The length of the longest consecutive 1s in the binary representation is: " + maxCount);
}
}
Python3
# Python program to find the length of the longest
# consecutive 1s in binary representation of
# a number.
def main():
num = 222
# Convert the integer to its binary representation as a string
binary = format(num, '032b')
count = 0
max_count = 0
# Loop through the binary string to find the longest consecutive 1s
for i in range(len(binary)):
if binary[i] == '1':
count += 1
if count > max_count:
max_count = count
else:
count = 0
# Print the result
print("The length of the longest consecutive 1s in the binary representation is:", max_count)
if __name__ == "__main__":
main()
C#
// C# program to find the length of the longest
// consecutive 1s in binary representation of
// a number.
using System;
public class LongestConsecutiveOnes
{
public static void Main(string[] args)
{
int num = 222;
// Convert the integer to its binary representation as a string
string binary = Convert.ToString(num, 2).PadLeft(32, '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[i] == '1')
{
count++;
if (count > maxCount)
{
maxCount = count;
}
}
else
{
count = 0;
}
}
// Print the result
Console.WriteLine("The length of the longest consecutive 1s in the binary representation is: " + maxCount);
}
}
JavaScript
// JavaScript program to find the length of the longest
// consecutive 1s in binary representation of
// a number.
function main() {
const num = 222;
// Convert the integer to its binary representation as a string
let binary = num.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;
}
}
// Print the result
console.log("The length of the longest consecutive 1s in the binary representation is:", maxCount);
}
main();
OutputThe length of the longest consecutive 1s in the binary representation is: 4
The time complexity of this algorithm is O(log n), where n is the given integer, since we iterate through the bits of the integer. The space complexity is O(1), since we only use constant extra space to store the variables max_len and cur_len.
Similar Reads
Length of longest consecutive zeroes in the binary representation of a number.
We have a number N. Determine the length of the longest consecutive 0's in its binary representation. Examples: Input : N = 14 Output : 1 Binary representation of 14 is 1110. There is only one 0 in the binary representation. Input : N = 9 Output : 2 A simple approach is to traverse through all bits
4 min read
Find consecutive 1s of length >= n in binary representation of a number
Given two integers x and n, the task is to search for the first consecutive stream of 1s (in the x's 32-bit binary representation) which is greater than or equal to n in length and return its position. If no such string exists then return -1.Examples: Input: x = 35, n = 2 Output: 31 Binary represent
10 min read
1 to n bit numbers with no consecutive 1s in binary representation.
Given a number n, our task is to find all 1 to n bit numbers with no consecutive 1s in their binary representation. Examples: Input : n = 4 Output : 1 2 4 5 8 9 10 These are numbers with 1 to 4 bits and no consecutive ones in binary representation. Input : n = 3 Output : 1 2 4 5 Recommended: Please
6 min read
1 to n bit numbers with no consecutive 1s in binary representation
Given a number n, our task is to find all 1 to n bit numbers with no consecutive 1s in their binary representation.Examples: Input: N = 4 Output: 1 2 4 5 8 9 10 These are numbers with 1 to 4 bits and no consecutive ones in binary representation. Input: n = 3 Output: 1 2 4 5 Approach: There will be 2
5 min read
Length of second longest sequence of consecutive 1s in a binary array
Given a binary array arr[] of size N, the task is to find the length of the second longest sequence of consecutive 1s present in the array. Examples: Input: arr[] = {1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0} Output: 4 3 Explanation: Longest sequence of consecutive ones is 4 i.e {arr[7], ... arr[10]}
7 min read
Find next greater element with no consecutive 1 in it's binary representation
Given Q queries where each query consists of an integer N and the task is to find the smallest integer greater than N such that there are no consecutive 1s in its binary representation. Examples: Input: Q[] = {4, 6} Output: 5 8 Input: Q[] = {50, 23, 456} Output: 64 32 512 Approach: Store all the num
8 min read
Length of longest consecutive ones by at most one swap in a Binary String
Given a Binary String of length N . It is allowed to do at most one swap between any 0 and 1. The task is to find the length of the longest consecutive 1's that can be achieved. Examples: Input : str = "111011101" Output : 7 We can swap 0 at 4th with 1 at 10th position Input : str = "111000" Output
9 min read
Length of longest connected 1âs in a Binary Grid
Given a grid of size N*M consists of 0 and 1 only, the task is to find the length of longest connected 1s in the given grid. We can only move to left, right, up or down from any current cell of the grid. Examples: Input: N = 3, M = 3, grid[][] = { {0, 0, 0}, {0, 1, 0}, {0, 0, 0} } Output: 1 Explanat
12 min read
Maximum number of consecutive 1's in binary representation of all the array elements
Given an array arr[] of N elements, the task is to find the maximum number of consecutive 1's in the binary representation of an element among all the elements of the given array. Examples: Input: arr[] = {1, 2, 3, 4} Output: 2 Binary(1) = 01 Binary(2) = 10 Binary(3) = 11 Binary(4) = 100 Input: arr[
6 min read
Length of the longest substring with consecutive characters
Given string str of lowercase alphabets, the task is to find the length of the longest substring of characters in alphabetical order i.e. string "dfabck" will return 3. Note that the alphabetical order here is considered circular i.e. a, b, c, d, e, ..., x, y, z, a, b, c, .... Examples: Input: str =
7 min read