Valid IPv4 Address
Problem
Read one word. Print true if it is a valid IPv4 address: exactly four numbers separated by dots, each number from 0 to 255, digits only, and no leading zeros (the number 0 itself is allowed).
Constraints
- 1 <= length <= 100, no spaces
Examples
Input
192.168.1.1
Output
true
Input
256.1.1.1
Output
false
Solutions
We check the shape first (four parts), then each part: only digits, not too long, no leading zero, and at most 255.
/*
* Problem : Process one line of text.
* Input : One line of text.
* Output : true or false.
* Approach: Check every part.
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static boolean solve(String s) {
// Step 1: Split at the dots. The limit -1 keeps empty parts at the end.
String[] parts = s.split("\\.", -1);
// Step 2: There must be exactly four parts.
if (parts.length != 4) {
return false;
}
for (String part : parts) {
// Step 3: Each part has 1 to 3 characters.
if (part.length() == 0 || part.length() > 3) {
return false;
}
// Step 4: Each character must be a digit.
for (char c : part.toCharArray()) {
if (c < '0' || c > '9') {
return false;
}
}
// Step 5: No leading zeros, and the value is at most 255.
if (part.length() > 1 && part.charAt(0) == '0') {
return false;
}
if (Integer.parseInt(part) > 255) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.hasNextLine() ? scanner.nextLine() : "";
System.out.println(solve(s));
}
}
Hints (1)
- How many parts must there be?