-1

例子:-

有效二进制数 = 1010111 // true

有效二进制点数 = 101011.11 // true

无效的二进制数 = 152.35 // false

如何检查?

4

2 回答 2

2

您可以使用正则表达式,[01]*\.?[01]+

演示:

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]+");
    }
}

输出:

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

regex101正则表达式的解释:

在此处输入图像描述

如果您还想匹配以可选0b或开头的数字0B,您可以使用正则表达式,(?:0[bB])?[01]*\.?[01]+

演示:

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]+");
    }
}

输出:

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

regex101正则表达式的解释:

在此处输入图像描述

于 2021-04-06T05:13:50.050 回答
-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;
}
于 2021-04-06T05:13:16.273 回答