import java.util.Scanner;
public class Test {
private static int decimalNum = 0;
private static String binary = "";
private static void getInput() {
Scanner sc = new Scanner(System.in);
System.out.println("Please type in a number");
decimalNum = sc.nextInt();
}
private static void convert() {
int decimalNumber = decimalNum;
String binaryNumber;
if (decimalNumber <= 0)
System.out.println("ERROR: entered integer is nonpositive.");
else {
binaryNumber = "";
while (decimalNumber != 0) {
// add spaces to separate 4-digit groups
if (binaryNumber.length() % 5 == 0)
binaryNumber = "" + binaryNumber;
// extract last digit in binary representation
// and add it to binaryNumber
binaryNumber = (decimalNumber % 2) + binaryNumber;
// cut last digit in binary representation
decimalNumber /= 2;
}
binary = binaryNumber;
System.out.println("Binary: " + binaryNumber);
}
}
public static void count() {
String s = binary + "";
System.out.println("Binary number: " + s);
int temp1Block = 0;
int temp0Block = 0;
int maxBlock = 0;
for (int i = 0; i < s.length(); i++) {
if ((s.charAt(i) == '1') && (i < s.length())) {
temp0Block = 0;
temp1Block++;
}
if ((s.charAt(i) == '0') && (i < s.length())) {
temp1Block = 0;
temp0Block++;
}
}
if (maxBlock < temp0Block) {
maxBlock = temp0Block;
}
if (maxBlock < temp1Block) {
maxBlock = temp1Block;
}
System.out.println("Maxblock " + maxBlock);
}
public static void main(String[] args) {
getInput();
convert();
count();
}
}
我不应该重置tempBlocks。并且有人可以帮我格式化我的代码,我不知道如何放置代码标签。
答案 0 :(得分:0)
我想你想跟踪最长的1或0序列。如果是这种情况,那么尝试将检查maxBlock条件的两个if语句放在循环中。
答案 1 :(得分:0)
我认为你的循环会更好一些:(我删除了'i'上的一些reduncant检查并简化了'maxBlock'的检查):
for(int i = 0; i < s.length(); ++i) {
if(s.charAt(i) == '1') {
// in case we were just keeping track of 0's
maxBlock = Math.max(maxBlock, temp0Count);
temp0Count = 0;
temp1Count++;
}
else {
// in case we were just keeping track of 1's
maxBlock = Math.max(maxBlock, temp1Count);
temp1Count = 0;
temp0Count++;
}
}