Is This a Valid Date?
Problem
Read three integers on one line: day, month and year. Print true if it is a real calendar date (leap years are considered), else false. The year is at least 1.
Constraints
- The line has three integers
Examples
Input
29 2 2024
Output
true
Input
29 2 2023
Output
false
Solutions
Checking only day <= 31 is a common mistake. A table of month lengths with a leap-year adjustment for February gives the exact rule. Check the month before using it as an index.
/*
* Problem : Process text.
* Input : One line of text.
* Output : true or false.
* Approach: Table of month lengths.
* Time : O(1)
* Space : O(1)
* 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: Read day, month and year from the line.
String[] part = s.trim().split("\\s+");
int day = Integer.parseInt(part[0]);
int month = Integer.parseInt(part[1]);
int year = Integer.parseInt(part[2]);
// Step 2: Check the simple limits first.
if (year < 1 || month < 1 || month > 12 || day < 1) {
return false;
}
// Step 3: February has 29 days in a leap year. Look up the days of the month in a table.
boolean leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
int[] days = {31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
return day <= days[month - 1];
}
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)
- Why check the month before the table lookup?