日期问题
小明正在整理一批历史文献。这些历史文献中出现了很多日期。
小明知道这些日期都在1960年1月1日至2059年12月31日。
令小明头疼的是,这些日期采用的格式非常不统一,有采用年/月/日的,有采用月/日/年的,
还有采用日/月/年的。更加麻烦的是,年份也都省略了前两位,
使得文献上的一个日期,存在很多可能的日期与其对应。
比如02/03/04,可能是2002年03月04日、2004年02月03日或2004年03月02日。
给出一个文献上的日期,你能帮助小明判断有哪些可能的日期对其对应吗?
输入
----
一个日期,格式是"AA/BB/CC"。 (0 <= A, B, C <= 9)
输入
----
输出若干个不相同的日期,每个日期一行,格式是"yyyy-MM-dd"。多个日期按从早到晚排列。
样例输入
----
02/03/04
样例输出
----
2002-03-04
2004-02-03
2004-03-02
下面先提供我的思路,接收三个数字,用数组保存,怎么判断要不要打印,才是关键。按题目的意思要求来说,一共有三种排列方式,那我就一一列举了,然后对每一个情况判断,年份要大于等于60或者小于等于59,月份再1~12内,日就要判断了,我这里用了一个数组保存每个月有多少天,还要判断平年瑞年,这样就完成了。有一个技巧,日期的格式化,我是硬凑的。目前自己写的,bug的话再看。
public class Main{
static int[]months= {31,29,31,30,31,30,31,31,30,31,30,31};
static Set<String>set=new TreeSet<>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str=sc.nextLine();
String[]date=str.split("/");
int[]nums=new int[3];
for(int i=0;i<3;i++) {
nums[i]=Integer.parseInt(date[i]);
}
print(nums[0],nums[1],nums[2]);
print(nums[2],nums[0],nums[1]);
print(nums[2],nums[1],nums[0]);
for(String iter:set)System.out.println(iter);
}
static void print(int year,int month,int day) {
if(month>=1&&month<=12&&day<=months[month-1]&&day>=1) {
if(year<=99&&year>=60) {
year+=1900;
}else if(year<=59&&year>=0) {
year+=2000;
}else return;
if(day==29&&!isRui(year))return;
String str = year+"-";
if((month+"").length()==1)str+="0"+month;
else str+=month;
str+="-";
if((day+"").length()==1)str+="0"+day;
else str+=day;
set.add(str);
}
}
static boolean isRui(int year) {
return !(year%4!=0||year%100==0&&year%400!=0);
}
}
接下来提供网络上的解法;
public class A07_日期问题 {
static boolean isLeap(int year) { // 闰年:2月29天;平年:2月28天
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}
static String f(int a, int b, int c) {
if (a >= 0 && a <= 59)
a += 2000;
else if (a >= 60 && a <= 99)
a += 1900;
else
return "";
if (b < 1 || b > 12)
return "";
if (c < 1 || c > 31)
return "";
boolean _isLeap = isLeap(a);
switch (b) { // 日期校验
case 2:
if (_isLeap && c > 29)
return "";
if (!_isLeap && c > 28)
return "";
break;
case 4:
case 6:
case 9:
case 11:
if (c > 30)
return "";
break;
default:
break;
}
String _a = a + "", _b = b + "", _c = c + "";
if (_b.length() == 1)
_b = "0" + _b;
if (_c.length() == 1)
_c = "0" + _c;
return _a + "-" + _b + "-" + _c;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String in = sc.nextLine();
int a = 0, b = 0, c = 0;
a = (in.charAt(0) - '0') * 10 + (in.charAt(1) - '0');
b = (in.charAt(3) - '0') * 10 + (in.charAt(4) - '0');
c = (in.charAt(6) - '0') * 10 + (in.charAt(7) - '0');
String case1 = f(a, b, c);
String case2 = f(c, a, b);
String case3 = f(c, b, a);
Set<String> ans = new TreeSet<String>(); // TreeSet带去重和排序功能
if (case1 != "")
ans.add(case1);
if (case2 != "")
ans.add(case2);
if (case3 != "")
ans.add(case3);
for (String s : ans) {
System.out.println(s);
}
}
}