Find longest sequence of 1’s in binary representation with one flip
Last Updated :
31 Oct, 2023
Give an integer n. We can flip exactly one bit. Write code to find the length of the longest sequence of 1 s you could create.
Examples:
Input : 1775
Output : 8
Binary representation of 1775 is 11011101111.
After flipping the highlighted bit, we get
consecutive 8 bits. 11011111111.
Input : 12
Output : 3
Input : 15
Output : 5
Input : 71
Output: 4
Binary representation of 71 is 1000111.
After flipping the highlighted bit, we get
consecutive 4 bits. 1001111.
A simple solution is to store the binary representation of a given number in a binary array. Once we have elements in a binary array, we can apply the methods discussed here.
An efficient solution is to walk through the bits in the binary representation of the given number. We keep track of the current 1’s sequence length and the previous 1’s sequence length. When we see a zero, update the previous Length:
- If the next bit is a 1, the previous Length should be set to the current Length.
- If the next bit is a 0, then we can’t merge these sequences together. So, set the previous Length to 0.
We update max length by comparing the following two:
- The current value of max-length
- Current-Length + Previous-Length .
- Result = return max-length+1 (// add 1 for flip bit count )
Below is the implementation of the above idea :
C++
#include<bits/stdc++.h>
using namespace std;
int flipBit(unsigned a)
{
if (~a == 0)
return 8* sizeof ( int );
int currLen = 0, prevLen = 0, maxLen = 0;
while (a!= 0)
{
if ((a & 1) == 1)
currLen++;
else if ((a & 1) == 0)
{
prevLen = (a & 2) == 0? 0 : currLen;
currLen = 0;
}
maxLen = max(prevLen + currLen, maxLen);
a >>= 1;
}
return maxLen+1;
}
int main()
{
cout << flipBit(13);
cout << endl;
cout << flipBit(1775);
cout << endl;
cout << flipBit(15);
return 0;
}
|
Java
class GFG
{
static int flipBit( int a)
{
if (~a == 0 )
{
return 8 * sizeof();
}
int currLen = 0 , prevLen = 0 , maxLen = 0 ;
while (a != 0 )
{
if ((a & 1 ) == 1 )
{
currLen++;
}
else if ((a & 1 ) == 0 )
{
prevLen = (a & 2 ) == 0 ? 0 : currLen;
currLen = 0 ;
}
maxLen = Math.max(prevLen + currLen, maxLen);
a >>= 1 ;
}
return maxLen + 1 ;
}
static byte sizeof()
{
byte sizeOfInteger = 8 ;
return sizeOfInteger;
}
public static void main(String[] args)
{
System.out.println(flipBit( 13 ));
System.out.println(flipBit( 1775 ));
System.out.println(flipBit( 15 ));
}
}
|
Python3
def flipBit(a):
if (~a = = 0 ):
return 8 * sizeof();
currLen = 0 ;
prevLen = 0 ;
maxLen = 0 ;
while (a > 0 ):
if ((a & 1 ) = = 1 ):
currLen + = 1 ;
elif ((a & 1 ) = = 0 ):
prevLen = 0 if ((a & 2 ) = = 0 ) else currLen;
currLen = 0 ;
maxLen = max (prevLen + currLen, maxLen);
a >> = 1 ;
return maxLen + 1 ;
print (flipBit( 13 ));
print (flipBit( 1775 ));
print (flipBit( 15 ));
|
C#
using System;
class GFG
{
static int flipBit( int a)
{
if (~a == 0)
{
return 8 * sizeof ( int );
}
int currLen = 0, prevLen = 0, maxLen = 0;
while (a != 0)
{
if ((a & 1) == 1)
{
currLen++;
}
else if ((a & 1) == 0)
{
prevLen = (a & 2) == 0 ? 0 : currLen;
currLen = 0;
}
maxLen = Math.Max(prevLen + currLen, maxLen);
a >>= 1;
}
return maxLen + 1;
}
public static void Main(String[] args)
{
Console.WriteLine(flipBit(13));
Console.WriteLine(flipBit(1775));
Console.WriteLine(flipBit(15));
}
}
|
Javascript
<script>
function flipBit(a)
{
if (~a == 0)
{
return 8 * sizeof(int);
}
let currLen = 0, prevLen = 0, maxLen = 0;
while (a != 0)
{
if ((a & 1) == 1)
{
currLen++;
}
else if ((a & 1) == 0)
{
prevLen = (a & 2) == 0 ? 0 : currLen;
currLen = 0;
}
maxLen = Math.max(prevLen + currLen, maxLen);
a >>= 1;
}
return maxLen + 1;
}
document.write(flipBit(13) + "</br>" );
document.write(flipBit(1775) + "</br>" );
document.write(flipBit(15));
</script>
|
PHP
<?php
function flipBit( $a )
{
if (~ $a == 0)
return 8 * sizeof();
$currLen = 0;
$prevLen = 0;
$maxLen = 0;
while ( $a != 0)
{
if (( $a & 1) == 1)
$currLen ++;
else if (( $a & 1) == 0)
{
$prevLen = ( $a & 2) == 0? 0 : $currLen ;
$currLen = 0;
}
$maxLen = max( $prevLen + $currLen , $maxLen );
$a >>= 1;
}
return $maxLen +1;
}
echo flipBit(13);
echo "\n" ;
echo flipBit(1775);
echo "\n" ;
echo flipBit(15);
?>
|
Time Complexity: O(log2n)
Auxiliary Space: O(1)
Approach 2: Sliding Window
In this approach, we can use a sliding window to count the length of the longest consecutive 1’s. We can use two pointers to define a window and keep track of the number of flips we have made. When we encounter a 0, we can flip it and move the right pointer to the right. If the number of flips we have made is greater than 1, we can move the left pointer to the right until we have made only one flip. We can then update the maximum length obtained so far.
Here’s the code:
C++
#include<bits/stdc++.h>
using namespace std;
int findMaxConsecutiveOnes( int num) {
int left = 0, right = 0, flips = 0, max_len = 0;
string binary = bitset<32>(num).to_string();
while (right < binary.size()) {
if (binary[right] == '0' ) {
flips++;
}
while (flips > 1) {
if (binary[left] == '0' ) {
flips--;
}
left++;
}
max_len = max(max_len, right - left + 1);
right++;
}
return max_len;
}
int main()
{
cout << findMaxConsecutiveOnes(13);
cout << endl;
cout << findMaxConsecutiveOnes(1775);
cout << endl;
cout << findMaxConsecutiveOnes(15);
return 0;
}
|
Java
public class Main {
public static int findMaxConsecutiveOnes( int num) {
int left = 0 , right = 0 , flips = 0 , max_len = 0 ;
String binary = String.format( "%32s" , Integer.toBinaryString(num)).replace( ' ' , '0' );
while (right < binary.length()) {
if (binary.charAt(right) == '0' ) {
flips++;
}
while (flips > 1 ) {
if (binary.charAt(left) == '0' ) {
flips--;
}
left++;
}
max_len = Math.max(max_len, right - left + 1 );
right++;
}
return max_len;
}
public static void main(String[] args) {
System.out.println(findMaxConsecutiveOnes( 13 ));
System.out.println(findMaxConsecutiveOnes( 1775 ));
System.out.println(findMaxConsecutiveOnes( 15 ));
}
}
|
Python3
def findMaxConsecutiveOnes(num):
left, right, flips, max_len = 0 , 0 , 0 , 0
binary = format (num, 'b' ).zfill( 32 )
while right < len (binary):
if binary[right] = = '0' :
flips + = 1
while flips > 1 :
if binary[left] = = '0' :
flips - = 1
left + = 1
max_len = max (max_len, right - left + 1 )
right + = 1
return max_len
if __name__ = = "__main__" :
print (findMaxConsecutiveOnes( 13 ))
print (findMaxConsecutiveOnes( 1775 ))
print (findMaxConsecutiveOnes( 15 ))
|
C#
using System;
class GFG
{
static int FindMaxConsecutiveOnes( int num)
{
int left = 0, right = 0, flips = 0, max_len = 0;
string binary = Convert.ToString(num, 2).PadLeft(32, '0' );
while (right < binary.Length)
{
if (binary[right] == '0' )
flips++;
while (flips > 1)
{
if (binary[left] == '0' )
flips--;
left++;
}
max_len = Math.Max(max_len, right - left + 1);
right++;
}
return max_len;
}
static void Main()
{
Console.WriteLine(FindMaxConsecutiveOnes(13));
Console.WriteLine(FindMaxConsecutiveOnes(1775));
Console.WriteLine(FindMaxConsecutiveOnes(15));
}
}
|
Javascript
function findMaxConsecutiveOnes(num) {
let left = 0;
let right = 0;
let flips = 0;
let max_len = 0;
let binary = num.toString(2).padStart(32, '0' );
while (right < binary.length) {
if (binary[right] === '0' ) {
flips++;
}
while (flips > 1) {
if (binary[left] === '0' ) {
flips--;
}
left++;
}
max_len = Math.max(max_len, right - left + 1);
right++;
}
return max_len;
}
console.log( "Max Consecutive 1's after flipping one bit in binary of 13:" , findMaxConsecutiveOnes(13));
console.log( "Max Consecutive 1's after flipping one bit in binary of 1775:" , findMaxConsecutiveOnes(1775));
console.log( "Max Consecutive 1's after flipping one bit in binary of 15:" , findMaxConsecutiveOnes(15));
|
Time Complexity: O(n), where n is the number of bits in the binary representation of the given number.
Space Complexity: O(1)
This article is contributed by Mr. Somesh Awasthi.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...