# Java program to find the length of the Longest Consecutive 1’s in Binary Representation of a given integer

The length of the longest consecutive 1’s in the binary representation of a given integer involves the length of the longest series of 1’s that occur together. An example of this is given as follows −

Number = 13
Binary representation = 1101

The length of the longest consecutive 1’s in binary representation of 13 = 2

A program that demonstrates this is given as follows −

## Example

Live Demo

public class Example {
public static void main(String strings[]) {
int num = 55;
int n = num;
int count = 0;
while (num!=0) {
num = (num & (num << 1));
count++;
}
System.out.println("The length of the longest consecutive 1's in binary representation of " + n + " is: " + count);
}
}

## Output

The length of the longest consecutive 1's in binary representation of 55 is: 3

Now let us understand the above program.

The value of the number is defined. Then, length of the longest consecutive 1's in binary representation of the number is found using a while loop and stored in count variable. Finally, the value of count is displayed. The code snippet that demonstrates this is given as follows −

int num = 55;
int n = num;
int count = 0;
while (num!=0) {
num = (num & (num << 1));
count++;
}
System.out.println("The length of the longest consecutive 1's in binary representation of " + n + " is: " + count);