Find longest sequence of 1’s in binary representation with one flip

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.


Input : 1775         
Output : 8 
Binary representation of 1775 is 11011101111.
After flipping the highlighted bit, we get 
consecutive 8 bits.

Input : 12         
Output : 3 

Input : 15
Output : 5

A simple solution is to store binary representation of given number in a binary array. Once we have elements in binary array, we can apply methods discussed here.

An efficient solution is to walk through the bits in binary representation of given number. We keep track of current 1’s sequence length and the previous l’s sequence length. When we see a zero, update previous Length:

  1. If the next bit is a 1, previous Length should be set to current Length.
  2. If the next bit is a 0, then we can’t merge these sequences together. So, set previous Length to 0.

We update max length (or result) by comparing following two:

  1. Current value of max length
  2. Current-Length + Previous-Length + 1.

Below is C++ implementation of above idea.

// C++ program to find maximum consecutive
// 1's in binary representation of a number
// after flipping one bit.
using namespace std;

int flipBit(unsigned a)
    /* If all bits are l, binary
       representation of 'a' has all 1s */
    if (~a == 0)
        return 8*sizeof(int);

    int currLen = 0, prevLen = 0;

    // We can always have a sequence of
    // at least one 1
    int maxLen = 1;

    while (a!= 0)
        // Current bit is a 1
        if ((a & 1) == 1)

        // Current bit is a 0
        else if ((a & 1) == 0)
            /* Update to 0 (if next bit is 0)
               or currLen (if next bit is 1). */
            prevLen = (a & 2) == 0? 0 : currLen;
            currLen = 0;

        // Update maxLen if required
        maxLen = max(prevLen + currLen + 1, maxLen);

        // Remove last bit (Right shift)
        a >>= 1;

    return maxLen;

// Driver code
int main()
   cout << flipBit(13);
   return 0;

Output :


This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Writing code in comment? Please use, generate link and share the link here.