曾有邪教称1999年12月31日是世界末日。当然该谣言已经不攻自破。还有人称今后的某个世纪末的12月31日,如果是星期一则会… 有趣的是,任何一个世纪末的年份的12月31日都不可能是星期一!! 于是,“谣言制造商”又修改为星期日…1999年的12月31日是星期五,请问:未来哪一个离我们最近的一个世纪末年(即xx99年)的12月31日正好是星期天(即星期日)? 请回答该年份(只写这个4位整数,不要写12月31等多余信息)
首先,我们学习Calendar的用法:
1.获取时间
Calendar cal = Calendar.getInstance();
System.out.println("年:"+cal.get(Calendar.YEAR));
System.out.println("月:"+cal.get(Calendar.MONTH) + 1);
System.out.println("日:"+cal.get(Calendar.DAY_OF_MONTH));
System.out.println("时:"+cal.get(Calendar.HOUR_OF_DAY));
System.out.println("分:"+cal.get(Calendar.MINUTE));
System.out.println("秒:"+cal.get(Calendar.MILLISECOND));
运行结果:
2.设置时间
假如我们设置国庆节的前一天
2020-09-30 23:59:59
Calendar cal = Calendar.getInstance();
cal.set(2020,8,30,23,59,59);
System.out.println(cal.getTime());
运行结果
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR,2018);
cal.set(Calendar.MONTH,Calendar.SEPTEMBER);
cal.set(Calendar.DAY_OF_MONTH,30);
cal.set(Calendar.HOUR_OF_DAY,23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
System.out.println(cal.getTime());
3.时间的计算
Calendar cal = Calendar.getInstance();
cal.set(2020,8,30,23,59,59);
System.out.println(cal.getTime());
cal.add(Calendar.SECOND, 1);
System.out.println(cal.getTime());
运行结果
Wed Sep 30 23:59:59 CST 2020
Thu Oct 01 00:00:00 CST 2020
题解:
import java.util.*;
public class Main{
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
for(int year = 1999;year < 10000;year += 100) {
cal.set(Calendar.YEAR,year);
cal.set(Calendar.MONTH,11);
cal.set(Calendar.DAY_OF_MONTH, 31);
System.out.println(year+" "+cal.get(Calendar.DAY_OF_WEEK));
if(cal.get(Calendar.DAY_OF_WEEK) == 1) {
break;
}
}
}
}
暴力解法:
import java.util.*;
public class Main{
public static void main(String[] args) {
int year = 1999;
int week = 4;
for(year = 1999;year < 10000;year++) {
if((year%100!=0&&year%4==0)||year%400==0) {
week = (week+366)%7;
}
else {
week = (week+365)%7;
}
if(year%100 == 99) {
System.out.println(year+" "+week);
}
}
}
}