Topic information
Find the largest continuous number of 1s in the binary digits corresponding to a byte number. For example, the binary number of 3 is 00000011, and the maximum is 2 continuous ones. This question contains multiple sets of sample input.
Input description : input a byte number
Output description : the number of consecutive 1s after the output is converted to binary
Example input :
3
5
Sample output :
2
1
Description
3的二进制表示是11,最多有2个连续的1。
5的二进制表示是101,最多只有1个连续的1。
coding
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MostContinueBit {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input ;
while ((input = br.readLine()) != null) {
String binaryNum = Integer.toBinaryString(Integer.valueOf(input));
int max = 0;
int index = 0;
char[] chArr = binaryNum.toCharArray();
for (int i=0; i<chArr.length; i++) {
if (chArr[i] == '1') {
if (index == 0) {
index = 1;
// 处理1这种只有1个1的特殊情况
max = Math.max(max, index);
} else {
// 连续1则index++
index++;
// 防止连续1后没有0间隔的后续位数,则这里须要将index赋给max
max = Math.max(max, index);
}
} else {
// 连续1之后有0隔开,这里index置0
if (index > 0) {
max = Math.max(max, index);
index = 0;
}
}
}
System.out.println(max);
}
}
}