用C++解决一下问题:求一个int类型数字对应的二进制数字中1的最大连续数,例如3的二进制为00000011,最大连续2个1。数据范围:数据组数:1<=t<=5,1<=n<=500000;输入描述:输入一个int类型数字;输出描述:输出转成二进制之后连续1的个数
时间: 2024-04-14 17:28:24 浏览: 121
以下是用 C++ 解决该问题的代码:
```cpp
#include <iostream>
int countConsecutiveOnes(int num) {
int maxCount = 0;
int currentCount = 0;
while (num > 0) {
if (num & 1) {
currentCount++;
maxCount = std::max(maxCount, currentCount);
} else {
currentCount = 0;
}
num >>= 1;
}
return maxCount;
}
int main() {
int t;
std::cin >> t;
while (t--) {
int n;
std::cin >> n;
int consecutiveOnes = countConsecutiveOnes(n);
std::cout << consecutiveOnes << std::endl;
}
return 0;
}
```
这段代码定义了一个 `countConsecutiveOnes` 函数,用于计算一个整数对应的二进制数字中连续的 1 的最大个数。在 `main` 函数中,首先读取数据组数 `t`,然后对每组数据进行处理。
`countConsecutiveOnes` 函数使用位运算来计算连续的 1 的个数。它通过不断地将整数右移并与 1 进行按位与运算,来检查最低位是否为 1。如果最低位为 1,则将当前连续计数加一,并更新最大连续计数;否则,将当前连续计数归零。最后返回最大连续计数。
在 `main` 函数中,对每组数据调用 `countConsecutiveOnes` 函数,并输出结果。
阅读全文
相关推荐


















