题解 | #求最大连续bit数#
求最大连续bit数
https://www.nowcoder.com/practice/4b1658fd8ffb4217bc3b7e85a38cfaf2
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num = in.nextInt();
String str = toBinary(num);
int temp = 0;//记录连续的1
int res = 0;//获得理想答案
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '1') {
temp++;//有1就+1
} else {
res = Math.max(res, temp);//获取最大的连续1
temp=0;//重置
}
}
if(res<temp)//如果出来时最后一次没有进else,就可能res<temp
res=temp;//小就改,用Math.max也行
System.out.println(res);
}
//把数字转为二进制字符串
public static String toBinary(int num) {
String str = "";
while (num > 0) {
str = num % 2 + str; //逆着加,第一个余数是最后一位的值..以此类推
num /= 2; //下一个循环时num是%2后的商
}
return str;
}
}
这里主要是把数字完整转成二进制,然后依次轮询判定,其实str可以直接是str+=num%2 得到一个逆序的二进制数,但是最后几位连续0就会直接没了,但是不影响,对本题可以这样化简

三奇智元机器人科技有限公司公司福利 94人发布