1. Topic
Given a 32-bit integer num, you can be a digit from 0 to 1. Please write a program to find the length of the longest you can get a string of 1's.
示例 1:
输入: num = 1775(11011101111)
输出: 8
示例 2:
输入: num = 7(0111)
输出: 4
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/reverse-bits-lcci
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
2. Problem Solving
- And the length of the continuous recording end 1
class Solution {
public:
int reverseBits(int num) {
if(num==0)
return 1;
int prevlen, prevEnd, maxlen = 0, count = 0, start=-1;
int curstart, curlen, curEnd;
map<int,pair<int,int>> continOne;//连续1,结束pos : {开始位置,个数}
for(int i = 0; i < 32; ++i)
{
if((num>>i)&1) //为1
{
if(start==-1)
start = i;
count++;
if(i == 31)
continOne[i] = make_pair(start,count);
}
else
{
if(count)
continOne[i-1] = make_pair(start,count);
count = 0;
start = -1;
}
}
auto it = continOne.begin();
prevlen = it->second.second;
prevEnd = it->first;
maxlen = prevlen+1;
it++;
for(; it != continOne.end(); ++it)
{
curEnd = it->first;
curstart = it->second.first;
curlen = it->second.second;
if(curstart - prevEnd == 2)
maxlen = max(maxlen, curlen+prevlen+1);
else
maxlen = max(maxlen, curlen+1);
prevlen = curlen;
prevEnd = curEnd;
}
return maxlen;
}
};
- Lite version
class Solution {
public:
int reverseBits(int num) {
int prevlen = 0, curlen = 0, maxlen = 0;
for(int i = 0; i < 32; ++i)
{
if((num>>i)&1) //为1
curlen++;
else
{
maxlen = max(maxlen, curlen+prevlen+1);
prevlen = curlen;
curlen = 0;
}
}
return maxlen;
}
};