【题目】
在X星系的广袤空间中漂浮着许多X星人造“炸弹”,用来作为宇宙中的路标。
每个炸弹都可以设定多少天之后爆炸。
比如:阿尔法炸弹2015年1月1日放置,定时为15天,则它在2015年1月16日爆炸。
有一个贝塔炸弹,2014年11月9日放置,定时为1000天,请你计算它爆炸的准确日期。
请填写该日期,格式为 yyyy-mm-dd 即4位年份2位月份2位日期。比如:2015-02-19
请严格按照格式书写。不能出现其它文字或符号。
【分析】按天循环,注意闰年,思路同《高斯日记》
【源码】
public class Test003 {
public static void main(String[] args) {
// 创建一个二维数组,表示每个月的天数
int[][] daysMonth = {
{ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } };
int sumDays = 0; // 经过的天数
int year = 2014;
int month = 10; // 初始化的月份是11月
int day = 9; //初始化的号是9
ok: while (true) {
int type = leapType(year);
int[] dm = daysMonth[type];
while (month < 12) {
while (day < dm[month]) {
sumDays++;
day++;
if (sumDays == 1000) {
break ok;
}
}
month++;
day = 0;
}
//进入下一年
month = 0;
year++;
}
System.out.println(year + "-" + (month + 1) + "-" + day);
}
// 如果是平年,返回0;如果是闰年,返回1
private static int leapType(int year) {
int flag;
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
flag = 1;
} else {
flag = 0;
}
return flag;
}
}
【结果】
2017-08-05
【解法2源码】
public static void main(String[] args) {
Calendar c = Calendar.getInstance();
//设置开始日期
c.set(2014, 10, 9);
//计算时间间隔,单位毫秒
long time1 = c.getTimeInMillis();
long x = 1000;
long time2 = time1 + x*24*60*60*1000;
//设置结束日期
c.setTimeInMillis(time2);
//打印结束日期
System.out.println(c.get(Calendar.YEAR)+"-"+
(c.get(Calendar.MONTH)+1)+"-"+c.get(Calendar.DAY_OF_MONTH));
}