Site icon

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

1. Examples to understand the problem statement.

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
Exit mobile version