- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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);
Advertisements