问题描述
描述
给定两个日期,计算这两个日期之间有多少个2月29日(包括起始日期)。
只有闰年有2月29日,满足以下一个条件的年份为闰年:
年份能被4整除但不能被100整除
年份能被400整除
输入
第一行为一个整数T,表示数据组数。
之后每组数据包含两行。每一行格式为”month day, year”,表示一个日期。month为{“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November” , “December”}中的一个字符串。day与year为两个数字。
数据保证给定的日期合法且第一个日期早于或等于第二个日期。
输出
对于每组数据输出一行,形如”Case #X: Y”。X为数据组数,从1开始,Y为答案。
数据范围
1 ≤ T ≤ 550
小数据:
2000 ≤ year ≤ 3000
大数据:
2000 ≤ year ≤ 2×109
样例输入
4
January 12, 2012
March 19, 2012
August 12, 2899
August 12, 2901
August 12, 2000
August 12, 2005
February 29, 2004
February 29, 2012
样例输出
Case #1: 1
Case #2: 0
Case #3: 1
Case #4: 3
思考:考虑中间有多少闰年
想法
找边界问题
- 1、找出两个时间中的前一个闰年,分别设为a,b(a位在a时刻上一个闰年(不包含a),b为在b时刻时上一次过得闰年(包含b))
- 2、 结果为 (b/4 - a/4 )-(b/100 - a/100) + (b/400 - a/400);
import java.util.Scanner;
/**
* Created by Risky on 2015/4/19.
*/
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
in.nextLine();
for (int i = 0; i < n; i++) {
long count = 0l;
Long a = findLeap(in.nextLine());
//count -= a/4
String fb = in.nextLine();
Long b = 0l;
if (fb.startsWith("February 29"))
b = Long.parseLong(fb.split("\\s+")[2]);
else
b = findLeap(fb);
count = b / 4 - a / 4;
count -= (b / 100 - a / 100);
count += (b / 400 - a / 400);
System.out.println("Case #" + (i + 1) + ": " + count);
}
}
private static Long findLeap(String a) {
a = a.replace(',', ' ');
String[] as = a.split("\\s+");
long year = Long.parseLong(as[2]);
if (as[0].equals("January") ||
(as[0].equals("February") && Integer.parseInt(as[1]) <= 29)) {
return nearLeapYear(year - 1);
}
return nearLeapYear(year);
}
private static Long nearLeapYear(long year) {
if ((year % 400 == 0) || (year % 100 != 0 && year % 4 == 0))
return year;
else {
while (!((year % 400 == 0) || (year % 100 != 0 && year % 4 == 0)))
year--;
return year;
}
}
}