知识点位运算
描述
对于给定的十进制整数 n,求解其二进制表示中,最长连续 1 段的长度。
输入描述:
输入一个十进制整数 n(1≦n≦5×10(5次幂))。
输出描述:
输出一个整数,表示 n 的二进制表示中,最长连续 1 段的长度。
示例1
输入:
200
输出:
2
说明:
在这个样例中,十进制 (200)10 等于二进制 (11 001 000)2,其中最长连续 1 段的长度为 2。
示例2
输入:
1023
输出:
10
说明:
在这个样例中,十进制 (1023)10 等于二进制 (1 111 111 111)2。
备注:
本题数据已规范为单组询问(2025/01/15)。
cc方法00:
/hj086_bits_max_00_vio_00.cc
cpp
// 暴力枚举
#include <iostream>
#include <vector>
using namespace std;
int GetMaxBit(int & n)
{
int cntMax = 0;
int count = 0;
while (n) {
if (n % 2) {
count++;
cntMax = max(cntMax, count);
} else {
count = 0;
}
n = n / 2;
}
return cntMax;
}
int main()
{
int n = 0;
while (cin >> n) {
cout << GetMaxBit(n) << endl;
}
return 0;
}
cc方法01:
/hj086_bits_max_00_vio_01.cc
cpp
// 暴力枚举
#include <iostream>
#include <vector>
using namespace std;
int GetMaxBit(int & n)
{
int count = 0;
for (; n != 0; count++) {
// 只有当 `i` 位和 `i+1` 位同时为1时,结果位才为1
// - 任何孤立的1(右侧是0)会被消除
// 连续1序列的尾部每次右移异或后会被截断一个,同时count++,全部截掉后连续1的个数就是count计数
n &= n << 1;
}
return count;
}
int main()
{
int n = 0;
while (cin >> n) {
cout << GetMaxBit(n) << endl;
}
return 0;
}
cc方法02:
/hj086_bits_max_00_vio_02.cc
cpp
// 暴力枚举
#include <iostream>
#include <vector>
using namespace std;
int GetMaxBit(int & n)
{
int count = 0;
int cntMax = 0;
for (; n != 0; ) {
if (n & 1) {
count++;
cntMax = max(cntMax, count);
} else {
count = 0;
}
n = n >> 1;
}
return cntMax;
}
int main()
{
int n = 0;
while (cin >> n) {
cout << GetMaxBit(n) << endl;
}
return 0;
}
cc方法03:
/hj086_bits_max_01_stl_00.cc
cpp
// stl
#include <iostream>
#include <vector>
#include <bitset>
#include <algorithm>
using namespace std;
int parse(string s)
{
vector<int> vec;
char ch = '1';
int count = 0;
for (auto it = s.begin(); it != s.end(); ++it) {
if (*it == ch) {
count++;
if (it == s.end() - 1) {
vec.push_back(count);
}
} else {
if (count > 0) {
vec.push_back(count);
}
count = 0;
}
}
sort(vec.begin(), vec.end());
return vec.back();
}
int GetMaxBit(const int & n)
{
bitset<32> bs(n);
string s = bs.to_string('0', '1');
return parse(s);
}
int main()
{
int n = 0;
while (cin >> n) {
cout << GetMaxBit(n) << endl;
}
return 0;
}