import java.util.*;
/**
* 判断子网掩码是否合法
*/
public class Main1801 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String s = sc.nextLine();
System.out.println(isTrue(s));
}
}
public static boolean isTrue(String s) {
String[] split = s.split("\\.");
if (split.length != 4)
return false;
StringBuilder builder = new StringBuilder();
for (String s1 : split) {
if (Integer.parseInt(s1) >= 0 && Integer.parseInt(s1) <= 255) { //若不在0-255之间,则返回false
String s2 = Long.toString(Long.parseLong(s1), 2); //每组转为二进制
while (s2.length() != 8) { //若转为二进制之后,长度不够8位,需要在前面补全0
s2 = new StringBuilder(s2).insert(0, 0).toString();
}
builder.append(s2);
} else {
return false;
}
}
String toString = builder.toString();
if (toString.equals("11111111111111111111111111111111") || toString.equals("00000000000000000000000000000000")) { //全1或者全0的子网掩码也是不合法的
return false;
}
for (int i = 0; i < toString.length() - 1; i++) {
String substring = toString.substring(i, i + 2);
if (substring.equals("01")) {//如何判断子网掩码是否合法,在最后拼接好的32位二进制字符串中查找,是否包含“01”,若包含则不合法
return false;
}
}
return true;
}
}
判断子网掩码是否合法-Java
最新推荐文章于 2024-09-11 14:17:12 发布