Home »
Java Programs »
Java Basic Programs
Java program to find the Length of Longest Sequence of 0's in binary form of a number
In this java program we are going to find the longest sequence of 0's of binary form of a number.
Submitted by Chandra Shekhar, on January 05, 2018
Given a number, we have to find its longest sequence of 0's using java program.
Example:
Input: 26
Output:
Binary form: 11010
Longest Sequence of 0's: 1
Input: 5269
Output:
Binary form: 1010010010101
Longest Sequence of 0's: 2
Program to find longest sequence of 0's in Java
import java.util.*;
public class LengthOfLongestSequence
{
public static void main(String[] args)
{
// declare and initialize here
int Num, rem, quot, i=1, j;
int bin_num[] = new int[100];
Scanner SC = new Scanner(System.in);
// enter number here.
System.out.print("Enter the number : ");
Num = SC.nextInt();
quot = Num;
// conert into binary number.
while(quot != 0)
{
bin_num[i++] = quot%2;
quot = quot/2;
}
String Str="";
System.out.print("Binary number is : ");
for(j=i-1; j>0; j--)
{
Str = Str + bin_num[j];
}
System.out.print(Str);
i = Str.length()-1;
while(Str.charAt(i)=='0')
{
i--;
}
int length = 0;
int ctr = 0;
for(; i>=0; i--)
{
if(Str.charAt(i)=='1')
{
length = Math.max(length, ctr);
ctr = 0;
}
else
{
ctr++;
}
}
length = Math.max(length, ctr);
System.out.println("\nLength of the longest sequence: "+length);
}
}
Output
First run:
Enter the number : 26
Binary number is : 11010
Length of the longest sequence: 1
Second run:
Enter the number : 5269
Binary number is : 1010010010101
Length of the longest sequence: 2
Java Basic Programs »