Created
September 20, 2017 11:28
-
-
Save javamultiplex/0d88eb3a1d6d076834d0c0155ce4e22e to your computer and use it in GitHub Desktop.
Given Number is Binary or not?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.javamultiplex.number; | |
import java.util.Scanner; | |
/** | |
* | |
* @author Rohit Agarwal | |
* @category Number Problems | |
* @problem Number is binary or not | |
* | |
*/ | |
public class BinaryNumber { | |
public static void main(String[] args) { | |
Scanner input = null; | |
try { | |
input = new Scanner(System.in); | |
System.out.println("Enter number : "); | |
String number = input.next(); | |
/* | |
* Regular expression that matches string containing only | |
* digits[0-9]. | |
*/ | |
String pattern1 = "^[0-9]+$"; | |
if (number.matches(pattern1)) { | |
/* | |
* Regular expression that matches string containing only binary | |
* digits[0-1]. | |
*/ | |
String pattern2 = "^[01]+$"; | |
if (number.matches(pattern2)) { | |
System.out.println("It is binary."); | |
} else { | |
System.out.println("It is not binary."); | |
} | |
} else { | |
System.out.println("Please enter valid number."); | |
} | |
} finally { | |
if (input != null) { | |
input.close(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment