题解 | #求最大连续bit数#--Integer方法及排序
求最大连续bit数
https://www.nowcoder.com/practice/4b1658fd8ffb4217bc3b7e85a38cfaf2
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextInt()) {
int num = in.nextInt();
// 转化为二进制字符串
String binaryStr = Integer.toBinaryString(num);
int count = Integer.bitCount(num);
if (count == 1) {
System.out.println(1);
} else if (count == 0) {
System.out.println(0);
} else {
// 统计所有1连续出现的次数
int consistCount = 0;
List<Integer> countList = new ArrayList<>();
for (int i = 0; i < binaryStr.length(); i++) {
if (binaryStr.charAt(i) == '1') {
consistCount++;
countList.add(consistCount);
} else {
consistCount = 0;
}
}
// 输出1最大连续出现次数
System.out.println(countList.stream().max(Integer :: compareTo).get());
}
}
}
}