题解 | #合法IP#
合法IP
http://www.nowcoder.com/practice/995b8a548827494699dc38c3e2a54ee9
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
String n = sc.nextLine();
String[] s = n.split("\\.");
if (s.length != 4) {
System.out.println("NO");
} else {
String res = getRes(s);
System.out.println(res);
}
}
}
private static String getRes(String[] s) {
for (String item : s) {
if ("".equals(item)) {
return "NO";
}
for (int j = 0; j < item.length(); j++) {
if (item.length() > 1 && item.charAt(0) == '0') {
return "NO";
}
if (!Character.isDigit(item.charAt(j))) {
return "NO";
}
}
}
for (String value : s) {
int num = Integer.parseInt(value);
if (num < 0 || num > 255) {
return "NO";
}
}
return "YES";
}
}