-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path06-16-ValidateIPAddress.java
More file actions
51 lines (44 loc) · 1.54 KB
/
06-16-ValidateIPAddress.java
File metadata and controls
51 lines (44 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution {
public String validIPAddress(String ip) {
if (ip.contains(":")) return ipv6(ip);
return ipv4(ip);
}
public String ipv4(String ip) {
int count = 0;
for (char x : ip.toCharArray()) {
if (x == '.') count++;
else if (!Character.isDigit(x)) return "Neither";
}
if (count != 3) return "Neither";
String[] domains = ip.split("\\.");
if (domains.length != 4) return "Neither";
for (String domain : domains) {
int len = domain.length();
if (len == 0 || len > 3) return "Neither";
if (len != 1 && domain.charAt(0) == '0') return "Neither";
if (Integer.parseInt(domain) > 255) return "Neither";
}
return "IPv4";
}
public String ipv6(String ip) {
int count = 0;
for (char x : ip.toCharArray()) {
if (x == ':') count++;
else if (!Character.isLetterOrDigit(x)) return "Neither";
}
if (count != 7) return "Neither";
String[] domains = ip.split(":");
if (domains.length != 8) return "Neither";
for (String domain : domains) {
int len = domain.length();
if (len == 0 || len > 4) return "Neither";
try {
long num = Long.parseLong(domain, 16);
if (len > 4 && domain.charAt(0) == '0') return "Neither";
} catch (NumberFormatException nfe) {
return "Neither";
}
}
return "IPv6";
}
}