Find the length of the longest sequence of zeros in binary representation of an integer
This Java program prompts the user to input a decimal number and converts it to binary. Then, it finds the length of the longest sequence of consecutive 0's in the binary representation.
- The program first initializes variables such as dec_num for decimal number, quo for quotient, i and j as counters and bin_num[] as an array to store binary digits.
- Next, the program takes input of decimal number from the user using the Scanner class and converts it into binary using a while loop. In this loop, the remainder of dec_num divided by 2 is stored in the bin_num[] array and dec_num is updated as dec_num divided by 2.
- After converting the decimal number to binary, the program creates a string variable bin_str to store the binary number as a string. It does this by concatenating each binary digit stored in the bin_num[] array, starting from the most significant bit.
- Next, the program finds the length of the longest sequence of consecutive 0's in the binary string. It does this by iterating through the string from right to left and counting the number of consecutive 0's. Whenever it encounters a 1, it compares the count with the previous maximum count and updates the maximum count if necessary.
- Finally, the program prints the length of the longest sequence of consecutive 0's in the binary representation.
Source Code
import java.util.*;
public class Find_Length
{
public static void main(String[] args)
{
int dec_num, quo, i=1, j;
int bin_num[] = new int[100];
Scanner scan = new Scanner(System.in);
System.out.print("Enter Decimal Number : ");
dec_num = scan.nextInt();
quo = dec_num;
while(quo != 0)
{
bin_num[i++] = quo%2;
quo = quo/2;
}
String bin_str = " ";
for(j=i-1; j>0; j--)
{
bin_str = bin_str + bin_num[j];
}
System.out.println("Binary Number : "+bin_str);
i = bin_str.length()-1;
while(bin_str.charAt(i)=='0')
{
i--;
}
int len = 0;
int ct = 0;
for(i=1; i>=0; i--)
{
if(bin_str.charAt(i)=='1')
{
len = Math.max(len, ct);
ct = 0;
}
else
{
ct++;
}
}
len = Math.max(len, ct);
System.out.println("Length of the Longest Sequence : "+len);
}
}
Output
Enter Decimal Number : 40
Binary Number : 101000
Length of the Longest Sequence : 1