Check Whether The Given Number Is Binary Or Not | Java Programs

Output:

Check Whether Number Is Binary Or Not ***

Enter Any Number: 1111
1111 is a binary number
-----------------------------------------
Check Whether Number Is Binary Or Not ***

Enter Any Number: 1201011
1201011 is not a binary number

Click Here For Java Online Compiler

Solution:

import java.util.Scanner;

public class CheckForBinary {

    static void isBinaryOrNot(int number) {
        boolean isBinary = true;

        int take = number;

        while (take != 0) {
            int temp = take % 10;   //Gives last digit of the number

            if (temp > 1) {
                isBinary = false;
                break;
            } else {
                take = take / 10;    //Removes last digit from the number
            }
        }

        if (isBinary) {
            System.out.println(number + " is a binary number");
        } else {
            System.out.println(number + " is not a binary number");
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Check Whether Number Is Binary Or Not ***" + "\n");
        System.out.print("Enter Any Number: ");
        isBinaryOrNot(scanner.nextInt());
    }
}
Share This :

Related Post



sentiment_satisfied Emoticon