Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Pattern Searching
  • Tutorial on Pattern Searching
  • Naive Pattern Searching
  • Rabin Karp
  • KMP Algorithm
  • Z Algorithm
  • Trie for Pattern Seaching
  • Manacher Algorithm
  • Suffix Tree
  • Ukkonen's Suffix Tree Construction
  • Boyer Moore
  • Aho-Corasick Algorithm
  • Wildcard Pattern Matching
Open In App
Next Article:
Check if a number is binary or not in Java
Next article icon

Check if a number is binary or not in Java

Last Updated : 11 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a number N, the task is to check first whether the given number is binary or not and its value should be greater than 1. print true if N is the binary representation else print false.

Examples: 

Input: N = 1010 
Output: true 
Explanation: 
Given number is greater than 1 and none of its digits is greater than 1. Thus, it is a binary number greater than 1.

Examples: N = 1234 
Output: false 
Explanation: 
Given number is greater than 1 but some of its digits { 2, 3, 4} are greater than 1. Thus, it is not a binary number. 

Iterative Approach: 

  1. Check if the number is less than or equal to 1. If it is then, print false.
  2. Else if number is greater than 1 then, check if every digits of the number is 1 or 0.
  3. If any digits of the number is greater than 1 then print false, else print true.

Below is the implementation of the above approach:

Java
// Java program for the above approach class GFG {      // Function to check if number     // is binary or not     public static boolean isBinaryNumber(int num)     {          // Return false if a number         // is either 0 or 1 or a         // negative number         if (num == 0 || num == 1 || num < 0) {             return false;         }          // Get the rightmost digit of         // the number with the help         // of remainder '%' operator         // by dividing it with 10         while (num != 0) {              // If the digit is greater             // than 1 return false             if (num % 10 > 1) {                 return false;             }             num = num / 10;         }         return true;     }      public static void main(String args[])     {         // Given Number N         int N = 1010;          // Function Call         System.out.println(isBinaryNumber(N));     } } 

Output
true 

Time Complexity: O(K), K is the number of digits in N 
Auxiliary Space: O(1)

Regular Expression Approach: 

1. Convert the number into string.

2. Create a Regular Expression as mentioned below:

regex = "[01][01]+";

where: 

  • [01][01] matches one of the following { "00", "01", "10", "11" }.
  • + matches one or more occurrence of previous regular expression

3. Match the given number with the regular expression. If it matches return true, else return false.

Below is the implementation of the above approach:

Java
// Java program for the above approach import java.util.regex.*; class GFG {      // Function to check number is     // binary or not     public static boolean isBinaryNumber(int num)     {          // Regex to check a number         // is binary or not         String regex = "[01][01]+";          // Match the given number with         // the regular expression         return Integer.toString(num).matches(regex);     }      // Driver Code     public static void main(String args[])     {         // Given Number         int N = 1010;         System.out.println(isBinaryNumber(N));     } } 

Output
true 

Time Complexity: O(K), K is the number of digits in N 
Auxiliary Space: O(1)
 


Next Article
Check if a number is binary or not in Java

P

prashant_srivastava
Improve
Article Tags :
  • Pattern Searching
  • Mathematical
  • Java Programs
  • DSA
  • binary-representation
  • java-regular-expression
  • regular-expression
Practice Tags :
  • Mathematical
  • Pattern Searching

Similar Reads

    Check if Two Integers are Equal or Not in Java
    Checking two integers equal or not in Java is done by various approaches. Arithmetic operatorComparison OperatorsString functionsXOR operatorComplement (~) and bit-wise (&) operator Example Input: FirstNumber = 15 SecondNumber= 15 Output: Numbers are same Input: FirstNumber = 15 SecondNumber= 25
    2 min read
    Java Program to Check if a Given Integer is Odd or Even
    A number that is divisible by 2 and generates a remainder of 0 is called an even number. All the numbers ending with 0, 2, 4, 6, and 8 are even numbers. On the other hand, number that is not divisible by 2 and generates a remainder of 1 is called an odd number. All the numbers ending with 1, 3, 5,7,
    7 min read
    Java Program to Check if two numbers are bit rotations of each other or not
    Given two positive integers x and y, check if one integer is obtained by rotating bits of other. Input constraint: 0 < x, y < 2^32 Bit Rotation: A rotation (or circular shift) is an operation similar to shift except that the bits that fall off at one end are put back to the other end.More info
    3 min read
    Java Program to Convert a Decimal Number to Binary & Count the Number of 1s
    As per the number system, default computations are carried over decimal numbers whose base is standardized as 10. Machine computes all the execution at the physical layer in 0s and 1s. So arises a need for a number system with base 2 known as a binary number system. A binary number can be converted
    4 min read
    Java Program to Convert Integer Values into Binary
    Given an integer in Java, your task is to write a Java program to convert this given integer into a binary number. Example: Input: = 45 Output: = 101101 Input: = 32 Output: = 100000 Integers: Integers are numbers whose base value is 10. The Integer or int data type is a 32-bit signed two’s complemen
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences