Wednesday, September 27, 2023

How to check if a given Number is Binary in Java? [Solved] Example

Today we will take a look at another simple programming exercise, write a program to check if a number is binary in Java. A number is said to be binary if it only contains either 0 or 1, for example, 1010 is a binary number but 1234 is not. You can not any library method to solve this problem, you need to write a function to check if the given number is binary, you can use basic constructs of Java programming language e.g. operators, keywords, control statements, etc. If you are a regular reader of Javarevisited, then you know that I love to share simple programming problems here.

Programming interview questions serve two purposes, first, they help beginners to apply their basic knowledge to do something which looks challenging at first, and second, they serve as good coding questions to differentiate candidates on Java interviews between who can program and who can not.

The classic FizzBuzz is one of such problems but there are a lot many, like Prime numbers, Fibonacci series, or factorial.

But if you truly want to test your candidate then you need to give them some questions which are not so popular. If a candidate can apply his programming knowledge to a problem he is seeing the first time, he is probably going to perform better than the candidate who has already seen the problem.

That's why I was always looking at programming problems, which are not difficult to solve but have some element of freshness and are not so common. This problem of checking whether a number is binary or not is not very different from converting decimal to binary, but it will pose a challenge for those programmers who can't code.





Java Program check if a number is binary in Java? Example

The logic of finding if a number is binary is extremely simple, probably simpler than FizzBuzz itself, all you need to do is to check every digit of the number to see if they are greater than 1 or not. If any digit is greater than 1 then it's not binary.

For first-timers challenge is how to write a loop to check every digit, well you need to remember one of the common tricks of programming. If you divide a number by 10 e.g. number/10, you reduce one digit from it and if you use the remainder operator e.g. number%10 then you will get the last digit of the number.

For example, 1234/10 will return 123 which means last digit 4 is removed and 1234%10 will return 4, which is the last digit. By using these two operators you can easily write a loop that can go through each digit and can check if it's greater than 1 or not.  

This property is very useful in solving problems that involve checking each digit e.g. finding if a number is palindrome or reversing a number.



Java Program to check if the given number is binary or not

Following is a complete Java program to show you how you can check if a given number is binary or not. It contains one method called isBinary(int number), which accepts a number and returns true if it's binary otherwise false.

/**
 * Java program to check if a number is binary or not. A number is said to be
 * binary, if it only contains 0 and 1.
 *
 * @author
 */
public class Binary{

    public static void main(String args[]) {

        System.out.printf("Does number %d is a binary number? %b %n",
    101, isBinary(101));
        System.out.printf("Does integer %d is a binary number? %b %n",
    121, isBinary(121));
        System.out.printf("Does %d is a binary number? %b %n",
    1011, isBinary(1011));
        System.out.printf("Does number %d is a binary number? %b %n",
    111111, isBinary(111111));
        System.out.printf("Does %d is a binary number? %b %n",
    1321, isBinary(1321));
    }

    /*
     * Java function to check if an integer is a binary number or not.
     */
    public static boolean isBinary(int number) {
        int copyOfInput = number;

        while (copyOfInput != 0) {
            if (copyOfInput % 10 > 1) {
                return false;
            }
            copyOfInput = copyOfInput / 10;
        }
        return true;
    }

}

Output:
Does number 101 is a binary number? true
Does integer 121 is a binary number? false
Does 1011 is a binary number? true
Does number 111111 is a binary number? true
Does 1321 is a binary number? false
You can see from the output that our function is behaving correctly if you enter 101 it returned true because it's a binary number, it only contains zero and one. 

On the other hand, if you call isBinary() method with 121 it returned false because 121 is not binary, it contains digit 2 which is not allowed in the binary number system.

That's all on how to check if a number is binary in Java. If you are a beginner then do as much of this kind of exercise as possible, this will help you to develop code sense. If you have been doing programming for some years, you can solve this kind of problem to get your coding mozo back and prepare well for programming interviews.

By the way, if you are looking for simple programming problems, you can check my list of Top 30 programming interview questions, there I have shared questions from several popular topics including String, Array, Data Structure, and Logic.

And lastly one question for you, what was the last coding problem asked to you on coding interviews? and did you able to solve it? what was your approach and anything you think would have done better at that time?

14 comments:

  1. and what if the input is a negative number, for example -1?

    ReplyDelete
  2. God or bad solution done by a junior?

    public static boolean isBinary(int number) {
    return Integer.toString(number).matches("[01]*");
    }

    ReplyDelete
  3. Anyone who can explain how do it work when they were using the statement (copyOfInput % 10 > 1)?
    Are they using the last digit? and greater than 1. I don't really understand how the code work but i understood the concept.

    ReplyDelete
  4. Always nice to read your short and to the point blog entries! And some constructive feedback: when teaching how to write/use TDD so that beginners learn this; Rewrite the main method into a test class with (possibly 5+) tests to verify the functionality.

    ReplyDelete
  5. @Brian When you do a modulo 10 on a number, this operation returns the right-most / last digit. If it is greater that 1, the number is not binary because it doesn't consist solely of 0s or 1s. When you divide by 10, you basically cut of the last digit.

    ReplyDelete
  6. All int are binary. The question should have been posed as "Is the base 10 representation of a non-negative integer contain only 0 or 1?"

    ReplyDelete
  7. Set sdfsdf = new HashSet();
    int iiisd = 0;
    while (ser.length() > iiisd) {
    sdfsdf.add(ser.charAt(iiisd));
    iiisd++;
    }

    ReplyDelete
  8. I think of 3 options to solve this, although they have been aforementioned by other readers.
    1. Break all the digits and check as you have done Javin
    2. Do a regex pattern match with [01]*
    3. Create a Set with 0 and 1, and try to add each digit of input number. In any case of add method returns false, conclude that the input number is not binary.

    Please mention if there are any other solutions.

    ReplyDelete
    Replies
    1. int n = 110101;
      String s = "" + n;
      s = s.replace("1", "");
      s = s.replace("0", "");
      if(s.length() == 0)
      System.out.print(n + " is binary);
      else System.out.print(n + " is not binary");

      Delete
  9. public static boolean binary(int binary) {
    try {
    Integer.parseInt(binary + "", 2);

    return true;
    } catch (NumberFormatException e) {
    return false;
    }
    }

    ReplyDelete
  10. I don't want to spoil it for you guys but in what universe exactly is a java int with a value like 101 or 1010101 a binary number?

    ReplyDelete
  11. package lovejava;

    import java.util.Scanner;

    public class BinaryOrNot {

    public static void main(String[] args) {


    System.out.println("Enter the number:");
    Scanner sc = new Scanner(System.in);
    long a= sc.nextLong();

    if(isBinary(a)==true){
    System.out.println("The number is Binary");
    }
    else{
    System.out.println("The number is non binary");
    }
    }
    public static boolean isBinary(long p){
    while(p!=0){
    if(p%10>1){
    return false;
    }


    p=p/10;
    }
    return true;





    }


    }

    ReplyDelete
  12. Whats wrong with

    If (number = 0 || number = 1)
    {
    Result is a b8nary
    }
    Else
    {
    Result not a binary
    }

    ReplyDelete
  13. System.out.println(new Integer(101).toString().matches("[01]+"));

    ReplyDelete