Find number of consecutive 1’s in a binary number in java (example)

  • Given a decimal number in java (base 10)
  • Find out number of consecutive 1’s in a binary number.

1. Examples to understand the problem statement.

    • Given a decimal number 10
      • Binary representation of decimal number 10 is 1010
      • Consecutive 1’s in binary representation is 1.
    • Given a decimal number 12
      • Binary representation of decimal number 12 is 1100
      • Consecutive 1’s in binary representation is 2.
    • Given a decimal number 7.
      • Binary representation of decimal number 7 is 111
      • Consecutive 1’s in binary representation is 3.

2. Program: number of consecutive 1’s in a binary number in java (example)

package org.learn;

import java.util.Scanner;

public class BinaryNumber {
    public static void main(String[] args) {

        System.out.printf("1. Enter any number :");
        Scanner scanner = new Scanner(System.in);

        int inputNumber = scanner.nextInt();

        int number = inputNumber;
        int contNumber = 0;
        int numberOfOnes = 0;
        while(number > 0) {

            int remainder = number %2;
            if(remainder == 1) {
                contNumber ++;

                if(contNumber > numberOfOnes)
                    numberOfOnes = contNumber;

            } else { //reset the contNumber
                contNumber = 0;
            }
            number = number/2;
        }

        System.out.printf("2. Consecutive 1's in number %d is :%d",inputNumber,numberOfOnes);
    }
}

3. Output: consecutive 1’s in a binary number in java (example)

1. Enter any number :10
2. Consecutive 1's in number 10 is :1

1. Enter any number :12
2. Consecutive 1's in number 12 is :2

1. Enter any number :7
2. Consecutive 1's in number 7 is :3
Scroll to Top