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

C++Server Side ProgrammingProgramming

Suppose we have one integer n. Inside that, we can make the one-bit flip to generate the longest sequence of 1s. Suppose the number is 13, so binary representation is 1101. If we make a one-bit flip as make 0 to 1, it will be 1111. This is the longest sequence of 1s

To solve this problem, we will walk through the bits of a given number. We will keep track of the current 1’s sequence length, and the previous 1’s sequence length. When a zero has found, then update the previous length. So if the next bit is 1, then the previous length should be set to the current length. If the next one is 0, then make previous as 0 again.

Example

 Live Demo

#include<iostream>
using namespace std;
int singleFlipMaxOnes(unsigned number) {
   if (~number == 0)
      return 8*sizeof(int);
   int curr = 0, prev = 0, max_size = 0;
   while (number!= 0) {
      if ((number & 1) == 1)
         curr++;
      else if ((number & 1) == 0) {
         prev = (number & 2) == 0? 0 : curr;
         curr = 0;
      }
      max_size = max(prev + curr, max_size);
      number >>= 1;
   }
   return max_size+1;
}
int main() {
   cout << "Maximum length of the sequence with 1s: " << singleFlipMaxOnes(13);
}

Output

Maximum length of the sequence with 1s: 4
raja
Published on 19-Dec-2019 10:03:09
Advertisements