当前位置:网站首页>【Day_11 0506】求最大连续bit数
【Day_11 0506】求最大连续bit数
2022-08-01 17:40:00 【安河桥畔】
求最大连续bit数
题目来源
牛客网:求最大连续bit数
题目描述
求一个int类型数字对应的二进制数字中1的最大连续数,例如3的二进制为00000011,最大连续2个1
数据范围:数据组数:1≤t≤5 ,1≤n≤500000
进阶:时间复杂度:O(logn) ,空间复杂度:O(1)
输入描述
输入一个int类型数字
输出描述
输出转成二进制之后连续1的个数
示例1
输入
200
输出
2
说明
200的二进制表示是11001000,最多有2个连续的1。
思路分析
- 求二进制的1,优先使用按位与的方法
- 和1按位与判断最低位是否为1,若为1则给计数器count自增,并与之前的最大值max比较,取两者较大的赋值给max,每次count自增后都要更新max的值,保证max始终保存的是最大值
- 如果中间出现一位不是1,那么连续便中断了,将计数器count置为0
- 每次相与后右移一位,判断下一位,直到输入的数为0
代码展示
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n = 0;
while (cin >> n)
{
int count = 0;
int max = 0;
while (n)
{
//和1相与,判断最低位是否为1
if ((n & 1) == 1)
{
count++;
if (count > max)
{
max = count;
}
}
//连续中断,count赋值为0
else
{
count = 0;
}
//每次将n右移一位
n >>= 1;
}
cout << max;
}
}
边栏推荐
- 浅谈大数据背景下数据库安全保障体系
- [供应链·案例篇]石油和天然气行业的数字化转型用例
- 表达式;运算符,算子;取余计算;运算符优先顺序
- 关于LocalDateTime的全局返回时间带“T“的时间格式处理
- B011 - 基于51的多功能指纹智能锁
- How can become a good architect necessary skills: painting for all the people praise the system architecture diagram?What is the secret?Quick to open this article and have a look!.
- 后台管理系统的权限思路
- QLineEdit学习与使用
- Pytorch|GAN在手写数字集上的复现
- 04 flink cluster construction
猜你喜欢

How can become a good architect necessary skills: painting for all the people praise the system architecture diagram?What is the secret?Quick to open this article and have a look!.

XAML WPF item groupBox control

GRUB2的零日漏洞补丁现已推出

B001 - 基于STM32的智能生态鱼缸

解决MySQL插入不了中文数据问题

The site is not found after the website is filed. You have not bound this domain name or IP to the corresponding site! The configuration file does not take effect!

素域和扩域

晶振工作原理详解

B005 – 基于STC8的单片机智能路灯控制系统

面经汇总-社招-6年
随机推荐
LeaRun.net快速开发动态表单
XAML WPF项目groupBox控件
浅谈大数据背景下数据库安全保障体系
ROS2系列知识(5):【参数】如何管理?
QT常用全局宏定义
GridControl helper class for DevExpress
【TDP加码福利】COS用户实践征文月,等你来投稿!!!
2022年深圳市促进大健康产业集群高质量发展的若干措施
2022年MySQL最新面试题
My new book has sold 10,000 copies!
QT basic functions, signals, slots
Daily Yuxian Big Defeat
数字化采购管理系统开发:精细化采购业务流程管理,赋能企业实现“阳光采购”
When custom annotations implement log printing, specific fields are blocked from printing
golang json 返回空值
2022.08月--pushmall推贴共享电商更新与开发计划
QLineEdit学习与使用
TCP million concurrent server optimization parameters
DBPack SQL Tracing 功能及数据加密功能详解
SQL函数 TO_CHAR(三)