Q:

Java program to find the Length of Longest Sequence of 0\'s in binary form of a number

belongs to collection: Java Basic Programs

0

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

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to find sum of factorials from 1 to N... >>
<< Java program to find cube 1 to N...