- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

#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

- Related Questions & Answers
- Largest number with binary representation is m 1’s and m-1 0’s in C++
- C# program to find the length of the Longest Consecutive 1’s in Binary Representation of a given integer
- Maximum 0’s between two immediate 1’s in binary representation in C++
- Binary representation of next greater number with same number of 1’s and 0’s in C Program?
- Java program to find the length of the Longest Consecutive 1’s in Binary Representation of a given integer
- 1’s and 2’s complement of a Binary Number?
- Program to find length of longest substring with 1s in a binary string after one 0-flip in Python
- Binary Tree Longest Consecutive Sequence in C++
- Find the Pattern of 1’s inside 0’s using C++
- Count 1’s in a sorted binary array in C++
- Find One’s Complement of an Integer in C++
- Find Index of 0 to be replaced with 1 to get longest continuous sequence of 1s in a binary array in C++
- Count subarrays with equal number of 1’s and 0’s in C++
- Count number of binary strings of length N having only 0’s and 1’s in C++
- Binary Tree Longest Consecutive Sequence II in C++

Advertisements