
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Advertisements