-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathValidIPAddress.java
More file actions
93 lines (66 loc) · 1.96 KB
/
Copy pathValidIPAddress.java
File metadata and controls
93 lines (66 loc) · 1.96 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/**
Things to remember:
1. Spilt a string by dot requires double slash
2. Get actual value of a number from character
int val = (int) c - 48;
3. Split function needs -1 to return trailing empty strings
4. Inbuilt functions like
Character.isDigit()
Character.isLetter()
Character.isLetterOrDigit()
*/
class Solution {
public boolean checkIPv4(String queryIP) {
String[] queryIPArray = queryIP.split("\\.", -1);
if (queryIPArray.length != 4) {
return false;
}
for(String query : queryIPArray) {
if (query.isEmpty()){
return false;
}
if (query.length() > 1 && query.charAt(0) == '0'){
return false;
}
int val = 0;
int factor = 1;
for (char c : query.toCharArray()) {
if (!Character.isDigit(c)) {
return false;
}
val = (val * factor) + (int) c - 48;
factor = 10;
}
if (val < 0 || val > 255) {
return false;
}
}
return true;
}
public boolean checkIPv6(String queryIP) {
String[] queryIPArray = queryIP.split("\\:", -1);
if (queryIPArray.length != 8) {
return false;
}
for(String query : queryIPArray) {
if (query.length() < 1 || query.length() > 4){
return false;
}
for (char c : query.toCharArray()) {
if (! ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || (c >= '0' && c <= '9')) ){
return false;
}
}
}
return true;
}
public String validIPAddress(String queryIP) {
if (checkIPv4(queryIP)){
return "IPv4";
} else if (checkIPv6(queryIP)){
return "IPv6";
} else {
return "Neither";
}
}
}