题解:
求一个int类型数字对应的二进制数字中1的最大连续数
方法一:
循环位移
思路:位运算。
对一个数循环右移,并在循环的过程中寻找连续1个数的最大值。
#include <bits/stdc++.h>
using namespace std;
int main(){
int x;
while(cin >> x){
int num=0;//连续1个数
int res=0;//维护连续1个数的最大值
while(x){//循环
if(x&1){
num++;//累加连续1的个数
}else{
res=max(res,num);//维护最大值
num=0;
}
x>>=1;
}
res=max(res,num);
cout << res << endl;
}
return 0;
}
时间复杂度:
空间复杂度:![]()
方法二:
除二取余法
思路:当数非零时,循环除二取余,在循环中寻找连续1个数的最大值。
#include <bits/stdc++.h>
using namespace std;
int main(){
int x;
while(cin >> x){
int num=0;//连续1个数
int res=0;//维护连续1个数的最大值
while(x){//循环
if(x%2){
num++;//累加连续1的个数
}else{
res=max(res,num);//维护最大值
num=0;
}
x/=2;
}
res=max(res,num);
cout << res << endl;
}
return 0;
}
时间复杂度:
空间复杂度:![]()



京公网安备 11010502036488号