法一:枚举所有日期(推荐)
private static int[] days= {0,31,28,31,30,31,30,31,31,30,31,30,31};
public static boolean check_valid(int date) {
int year=date/10000;
int month=date/100%100;
int day=date%100;
if(month<1||month>12)return false;
if(month!=2&&day>days[month]||day<1)return false;//day要大于0
if(month==2) {
int leap=0;
if(year%4==0&&year%100!=0||year%400==0)
leap=1;
if(day>28+leap)return false;
}
return true;
}
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
String[] strings=scanner.next().split("/");
int a=Integer.parseInt(strings[0]);
int b=Integer.parseInt(strings[1]);
int c=Integer.parseInt(strings[2]);
for(int i=19600101;i<=20591231;i++) {//从小到大,已经排好序了
int year=i/10000;
int month=i/100%100;
int day=i%100;
if(check_valid(i)) {
if(year%100==a&&month==b&&day==c||
month==a&&day==b&&year%100==c||
day==a&&month==b&&year%100==c) {
System.out.print(year+"-");
if(month<10)System.out.print("0");
System.out.print(month+"-");
if(day<10)System.out.print("0");
System.out.println(day);
}
}
}
}
法二:根据给出的日期进行拼凑(考虑步骤较多)
private static Map<Integer, String> map=new HashMap<Integer, String>();
private static int[] days= {0,31,28,31,30,31,30,31,31,30,31,30,31};
public static boolean check_valid(int date) {
int year=date/10000;
int month=date/100%100;
int day=date%100;
if(month<1||month>12)return false;
if(month!=2&&day>days[month]||day<1)return false;//注意可能为00
if(month==2) {
int leap=0;
if(year%4==0&&year%100!=0||year%400==0)
leap=1;
if(day<1||day>28+leap)return false;
}
return true;
}
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
String string=scanner.next();
String aString=string.substring(0,2),bString=string.substring(3,5),cString=string.substring(6,8);
String[] A= {aString,cString,cString};
String[] B= {bString,aString,bString};
String[] C= {cString,bString,aString};
for(int i=0;i<3;i++) {
int date;
date=20*100+Integer.parseInt(A[i]);
date=date*100+Integer.parseInt(B[i]);
date=date*100+Integer.parseInt(C[i]);
if(19600101<=date&&date<=20591231&&check_valid(date)) {
if(!map.containsKey(date))
map.put(date, Integer.toString(date));
}
date=date-1000000;
if(19600101<=date&&date<=20591231&&check_valid(date)) {
if(!map.containsKey(date))
map.put(date, Integer.toString(date));
}
}
int[] arr=new int[map.size()];
int i=0;
for (Entry<Integer, String> entry : map.entrySet()) {
arr[i++]=entry.getKey();
}
Arrays.sort(arr);
for(int a:arr) {
String str=map.get(a);
System.out.println(str.substring(0,4)+"-"+str.substring(4,6)+"-"+str.substring(6,8));
}
}
狠人
闰年跟2月有什么关系吗?
闰年二月多一天