题解 | #求最大连续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 n = in.nextInt();
String str = intToStr2(n);
int max = getLength(str);
System.out.println(max);
}
private static int getLength(String str) {
int max = 0;
int length = str.length();
for (int i = 0; i < length; i++) {
if (str.charAt(i) == '1') {
int count = 0;
for (int j = i; j < length; j++) {
if (str.charAt(j) == '1') {
count++;
} else {
break;
}
}
max = Math.max(max, count);
}
}
return max;
}
private static String intToStr2(int n) {
String s = "";
while (n != 0) {
int yushu = n % 2;
s = yushu + s;
n = n / 2;
}
return s;
}
}
解题思路:
1, 先将整数转化为二进制字符串,
2, 再对二进制字符串进行遍历, 就能找到最长的字符串.
查看28道真题和解析