問題描述
描述
給定兩個日期,計算這兩個日期之間有多少個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;
}
}
}