1.题目描述
链接https://www.nowcoder.com/questionTerminal/4b1658fd8ffb4217bc3b7e85a38cfaf2?toCommentId=194442
功能: 求一个byte数字对应的二进制数字中1的最大连续数,例如3的二进制为00000011,最大连续2个1
输入: 一个byte型的数字
输出: 无
返回: 对应的二进制数字中1的最大连续数
2.思路分析
- 主要理解&运算符就可
- 1 & 1 = 1,0 &1 = 0,1 & 0 = 0, 0 & 0 =0;
- 这里如果右移之后还是1 的话,那就count++
- 否则就寻找另一个有1 的地方
3.代码实现
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n;
while(cin >> n)
{
int Max = 0;
for(int i = 0; i < 8; i++)
{
int count = 0;
// &:如果一直是1的话,那就count++
while((n >> i) & 1 == 1)
{
count++;
i++;
}
// 比较最大值
if(count > Max)
Max = count;
}
cout << Max <<endl;
}
return 0;
}