Java program to calculate consecutive 1’s in Binary Numbers

In this tutorial, we will learn how to calculate the number of consecutive 1’s in a given binary number in Java with simple and good logic. We encounter this problem in many situations, so this code will be useful for your requirements.

I know that you were here to learn some easy tricks to calculate consecutive 1’s then this is the perfect platform for you to refer.you can also learn the use of logical shift operator which is useful in many applications. Let us see the program…¬†

Calculate or find Consecutive 1’s in Binary Number in Java

Let us learn with some examples:

At first, create a variable which holds the input given by the user.

int binnumber;
System.out.println("Enter the Binary Number:");

Then call the function which will calculate consecutive 1’s in binary number by passing variable as argument and store that in sol variable.

int sol=getConsecutiveCount(binnumber);

Define a function which returns number of consecutive 1’s in given binary number.




public getConsecutiveCount(int inputNumber){}

one trick to find consecutive 1’s is the use of &operator and left shift(<<) operator. The code will be like

int count = 0 ;
  while(inputNumber != 0)
  {
     inputNumber = inputNumber & (inputNumber << 1);
   count++;
  }

For example, 1110 is the input,

this left shift(1110<<1) will be 1100 and final output(1110 & 1100) will be 1100 so every time zero will be added to the result and we iterate until the whole number is zero. For each iteration count is incremented to indicate these many numbers of 1’s are consecutive and return the count value. This count will be stored in sol.

Java program:

public getConsecutiveCount(int inputNumber)
{
  int count = 0 ;
  while(inputNumber != 0)
  {
     inputNumber = inputNumber & (inputNumber << 1);
   count++;
  }
return count;
}
class Solve
{
  public static void main(String args[])
  {
int binnumber,sol;
System.out.println("enter the binary number");
sol=getConsecutiveCount(binNumber);
System.out.println(sol);
}
}
output will be:

enter the binary number:110

2

Also learn:


Leave a Reply

Your email address will not be published. Required fields are marked *