【牛客】 [编程题]求最大连续bit数 C++

1.题目描述

链接https://www.nowcoder.com/questionTerminal/4b1658fd8ffb4217bc3b7e85a38cfaf2?toCommentId=194442

功能: 求一个byte数字对应的二进制数字中1的最大连续数,例如3的二进制为00000011,最大连续2个1
输入: 一个byte型的数字
输出: 无
返回: 对应的二进制数字中1的最大连续数

2.思路分析

  1. 主要理解&运算符就可
  2. 1 & 1 = 1,0 &1 = 0,1 & 0 = 0, 0 & 0 =0;
  3. 这里如果右移之后还是1 的话,那就count++
  4. 否则就寻找另一个有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;
}

猜你喜欢

转载自blog.csdn.net/weixin_43967449/article/details/106709963