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 lot many, e.g. 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 has some element of freshness and 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.

Also, basic knowledge of essential data structure and algorithms is also very important and that's why I suggest all Java programmers join a comprehensive Data Structure and Algorithms course like

##

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.

###

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.

That's all on

The Coding Interview Bootcamp: Algorithms + Data Structures

Data Structures and Algorithms: Deep Dive Using Java

Algorithms and Data Structures - Part 1 and 2

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.

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 lot many, e.g. 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 has some element of freshness and 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.

Also, basic knowledge of essential data structure and algorithms is also very important and that's why I suggest all Java programmers join a comprehensive Data Structure and Algorithms course like

**Data Structures and Algorithms: Deep Dive Using Java**on Udemy to improve your knowledge and algorithms skills.##
__Java Program check if a number is binary in Java__

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.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./** * 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

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.**Further Learning**The Coding Interview Bootcamp: Algorithms + Data Structures

Data Structures and Algorithms: Deep Dive Using Java

Algorithms and Data Structures - Part 1 and 2

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.

## 15 comments :

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

God or bad solution done by a junior?

public static boolean isBinary(int number) {

return Integer.toString(number).matches("[01]*");

}

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.

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.

@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.

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?"

Set sdfsdf = new HashSet();

int iiisd = 0;

while (ser.length() > iiisd) {

sdfsdf.add(ser.charAt(iiisd));

iiisd++;

}

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.

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");

public static boolean binary(int binary) {

try {

Integer.parseInt(binary + "", 2);

return true;

} catch (NumberFormatException e) {

return false;

}

}

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?

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;

}

}

Whats wrong with

If (number = 0 || number = 1)

{

Result is a b8nary

}

Else

{

Result not a binary

}

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

package com.app;

import java.util.Scanner;

public class AddTwoBinaryNumber {

public static void main(String[] args) {

int num1, num2; //for user intput for binary number

int digit1, digit2, sum=0, carry=0;

int[] arr = new int[10];

Scanner sc = new Scanner(System.in);

System.out.println("Enter 1st Binary Number in 1 or 0");

num1 = sc.nextInt();

System.out.println("Enter 2st Binary Number in 1 or 0");

num2 = sc.nextInt();

for(int j =arr.length-1; j>=0; j--)

{

digit1 = num1 % 10;

digit2 = num2 % 10;

num1 = num1 % 10;

num1 = num2 % 10;

sum = digit1 + digit2 + carry;

if(sum==0)

{

arr[j] = 0;

carry = 0;

}

else if(sum==1)

{

arr[j] = 1;

carry = 0;

}

else if(sum==2)

{

arr[j] = 0;

carry = 1;

}

else if(sum==3)

{

arr[j] = 1;

carry = 1;

}

}

for(int j =0; j<arr.length; j++)

{

System.out.print(arr[j]);

}

}

}

## Post a Comment