-
Notifications
You must be signed in to change notification settings - Fork 19
/
bestbefore.java
104 lines (77 loc) · 2.17 KB
/
bestbefore.java
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
94
95
96
97
98
99
100
101
102
103
104
import java.util.Arrays;
import java.util.Scanner;
public class bestbefore {
public static String earliestValidDate(int[] nums) {
if (isValidDate(nums[0] , nums[1] , nums[2]))
return convertYear(nums[0]) + "-" + nums[1] + "-" + nums[2];
if (isValidDate(nums[0] , nums[2] , nums[1]))
return convertYear(nums[0]) + "-" + nums[2] + "-" + nums[1];
if (isValidDate(nums[1] , nums[0] , nums[2]))
return convertYear(nums[1]) + "-" + nums[0] + "-" + nums[2];
if (isValidDate(nums[1] , nums[2] , nums[0]))
return convertYear(nums[1]) + "-" + nums[2] + "-" + nums[0];
if (isValidDate(nums[2] , nums[0] , nums[1]))
return convertYear(nums[2]) + "-" + nums[0] + "-" + nums[1];
if (isValidDate(nums[2] , nums[1] , nums[0]))
return convertYear(nums[2]) + "-" + nums[1] + "-" + nums[0];
return "";
}
public static String zeroPadding(String date) {
if (date.isEmpty())
return date;
if (date.charAt(6) == '-')
date = date.substring(0 , 5) + "0" + date.substring(5);
if (date.length() < 10)
date = date.substring(0 , 8) + "0" + date.substring(8);
return date;
}
public static boolean isLeapYear(int year) {
if (year % 400 == 0)
return true;
if (year % 100 == 0)
return false;
if (year % 4 == 0)
return true;
return false;
}
public static int convertYear(int num) {
if (num / 100 == 0)
return 2000 + num;
return num;
}
public static boolean isValidDate(int year , int month , int day) {
year = convertYear(year);
if (year < 2000 || year > 2999 || month < 1 || month > 12 || day < 1 || day > 31)
return false;
if (month == 2)
{
if (isLeapYear(year))
return day <= 29;
else
return day <= 28;
}
if (month < 8)
{
if (month % 2 == 1)
return day <= 31;
else
return day <= 30;
}
if (month % 2 == 1)
return day <= 30;
else
return day <= 31;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String date = scan.next();
String[] dates = date.split("/");
int[] nums = new int[3];
for (int i = 0; i < 3; i++)
nums[i] = Integer.parseInt(dates[i]);
Arrays.sort(nums);
String str = zeroPadding(earliestValidDate(nums));
System.out.println(str.isEmpty() ? date + " is illegal" : str);
scan.close();
}
}