-1

Examples:-

Valid Binary number = 1010111 // true

Valid Binary point number = 101011.11 // true

Invalid Binary number = 152.35 // false

How to check?

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Meet Bhavsar
  • 442
  • 6
  • 12

2 Answers2

2

You can use the regex, [01]*\.?[01]+

Demo:

import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        //Test
        Stream.of(
                    "1010111",
                    "101011.11",
                    "101.011.11",
                    "152.35"
                ).forEach(s -> System.out.println(s + " => " + isBinary(s)));
    }
    
    static boolean isBinary(String s) {
        return s.matches("[01]*\\.?[01]+");
    }
}

Output:

1010111 => true
101011.11 => true
101.011.11 => false
152.35 => false

Explanation of the regex at regex101:

enter image description here

If you also want to match a number starting with optional 0b or 0B, you can use the regex, (?:0[bB])?[01]*\.?[01]+

Demo:

import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        //Test
        Stream.of(
                    "1010111",
                    "0b1010111",
                    "0B1010111",
                    "1b010111",
                    "010B10111",
                    "101011.11",
                    "101.011.11",
                    "152.35"
                ).forEach(s -> System.out.println(s + " => " + isBinary(s)));
    }
    
    static boolean isBinary(String s) {
        return s.matches("(?:0[bB])?[01]*\\.?[01]+");
    }
}

Output:

1010111 => true
0b1010111 => true
0B1010111 => true
1b010111 => false
010B10111 => false
101011.11 => true
101.011.11 => false
152.35 => false

Explanation of the regex at regex101:

enter image description here

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
-1
public boolean isBinary(int num)
{
  // here you may want to check for negative number & return false if it is -ve number

 while (num != 0) {    
   if (num % 10 > 1) {
      return false;    // If the digit is greater than 1 return false
   }
   num = num / 10;
 }
 return true;
}
AbhiN
  • 642
  • 4
  • 18