在C++中查找二进制表示中通过一次翻转可获得的最长1序列
假设我们有一个整数n。在其中,我们可以进行一位翻转以生成最长的1序列。假设数字是13,则二进制表示为1101。如果我们进行一位翻转,将0变为1,它将变为1111。这是最长的1序列。
为了解决这个问题,我们将遍历给定数字的位。我们将跟踪当前的1序列长度和之前的1序列长度。当找到一个零时,更新之前的长度。因此,如果下一位是1,则之前的长度应设置为当前长度。如果下一个是0,则再次将之前设置为0。
示例
#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);
}输出
Maximum length of the sequence with 1s: 4
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP