问题描述
示例:-
有效二进制数 = 1010111 // 真
有效二进制点数 = 101011.11 // 真
无效的二进制数 = 152.35 // 错误
如何检查?
解决方法
您可以使用正则表达式,[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","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 处正则表达式的解释:
,替代方案:
使用Integer.parseInt:
Integer.parseInt("1010111",2)
上下文和测试台中的解析器:
public static void main(String[] args) {
String input1 = "1010111"; // true
String input2 = "101011.11"; // true
String input3 = "152.35"; // false
String input4 = "11.00.10"; // false
System.out.println(input1 + " -> " + isBinary(input1));
System.out.println(input2 + " -> " + isBinary(input2));
System.out.println(input3 + " -> " + isBinary(input3));
System.out.println(input4 + " -> " + isBinary(input4));
}
public static boolean isBinary(String input) {
List<String> blocks = Arrays.asList(input.split("\\."));
if(blocks.size() <= 2) {
try {
blocks.stream().map(block -> Integer.parseInt(block,2)).collect(Collectors.toList());
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
return false;
}
输出:
1010111 -> true
101011.11 -> true
152.35 -> false
11.00.10 -> false
,
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;
}