题解 | #求最大连续bit数#

求最大连续bit数

https://www.nowcoder.com/practice/4b1658fd8ffb4217bc3b7e85a38cfaf2

// HJ86 求最大连续bit数.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include<iostream>
#include<bits/stdc++.h>

using namespace std;

int main()
{
	int n;
	while (cin >> n)
	{
		int max_count = 0;//记录最大连续值
		int count = 0;//记录当前连续值
		while (n)
		{
			if (n % 2 == 1) {//对2取余得1则计数加一
				count++;
			}
			else {
				max_count = max(max_count, count);//遇0则更新当前最大值
				count = 0;
			}
			n /= 2;//n向右移一位
		}
		max_count = max(max_count, count);//判断最有一次连续的1
		cout << max_count << endl;
	}
	return 0;
}

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务