- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 Articles
- C# program to find the length of the Longest Consecutive 1’s in Binary Representation of a given integer
- Java program to find the length of the Longest Consecutive 1’s in Binary Representation of a given integer
- Largest number with binary representation is m 1’s and m-1 0’s in C++
- 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++
- 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?
- Binary Tree Longest Consecutive Sequence II in C++
- Find Index of 0 to be replaced with 1 to get longest continuous sequence of 1s in a binary array in C++
- Find Indexs of 0 to be replaced with 1 to get longest continuous sequence of 1s in a binary array - Set-2 in C++
- Find Indexs of 0 to be replaced with 1 to get longest continuous sequence of 1s in a binary array - Set-2 in Python
- Longest Arithmetic Sequence in C++
- Flip Equivalent Binary Trees in C++
- Program to find longest consecutive run of 1 in binary form of a number in C++
- Python program to find the length of the largest consecutive 1's in Binary Representation of a given string.

Advertisements