How can I count in Java the maximum consecutive 1's from a binary number? For instance, the user enters an integer like 13 this would be in binary 1101. The binary number 1101 has 2 consecutive one's, so the output should be 2. Another example the number 5 would be in binary 0101, so the output should be 1. My program doesn't work correctly if I type the number 439.
Scanner scanner = new Scanner(System.in);
int numb = scanner.nextInt();
int tempCount = 0;
int count = 0;
// numb = 439 -> output 3
// numb = 13 -> output 2
// numb = 1 -> output 1
while (numb >= 1) {
if (numb % 2 != 0) {
tempCount++;
numb /= 2;
count = tempCount;
if (numb % 2 != 0) {
tempCount++;
count = tempCount;
numb /= 2;
}
}
else {
numb /= 2;
tempCount = 0;
}
}
System.out.println(count);
I figured it out, here is the solution. I have forgotten an nested if statement.
Scanner scanner = new Scanner(System.in);
int numb = scanner.nextInt();
int tempCount = 0; //save temporarily the longest sequence of one's in this variable
int count = 0; // before the sequence of one's gets interrupted, I save the value from tempCount in count
// numb = 439 -> output 3
// numb = 13 -> output 2
// numb = 1 -> output 1
while (numb >= 1) {
if (numb % 2 != 0) {
tempCount++;
numb /= 2;
if(count < tempCount){
count = tempCount;
}
}
else {
numb /= 2;
tempCount = 0;
}
}
System.out.println(count);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With