给定两个日期,计算这两个日期之间有多少个2月29日(包括起始日期)。
只有闰年有2月29日,满足以下一个条件的年份为闰年:
1. 年份能被4整除但不能被100整除
2. 年份能被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
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Main { class Date{ public Date(int day, int month, int year) { this.day = day; this.month = month; this.year = year; } int day,month,year; } String month[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November" , "December"}; Map<String,Integer> mapMonth = new HashMap<>(); private void initMonth(){ for(int i=0;i<month.length;i++){ mapMonth.put(month[i], i+1); } } private int coutNum(String start,String end){ Date st = date(start); Date ed = date(end); int res = 0; for(int i=((st.year-1)/4+1)*4;i<=ed.year/4*4;i+=4){ if(i%400==0){ res += (ed.year/400-i/400)*97; res++; i = ed.year/400*400; }else{ if(isRun(i))res++; } } if(isRun(st.year)){ if(st.month>2){ res--; } } if(isRun(ed.year)){ if(ed.month<2){ res--; }else if(ed.month==2){ if(ed.day < 29) res--; } } return res; } private boolean isRun(int year){ if((year%4==0&&year%100!=0)||(year%400==0)) return true; return false; } private Date date(String str){ String s[] = str.split(" "); int month = mapMonth.get(s[0]); int year = Integer.parseInt(s[2]); int day = Integer.parseInt(s[1].substring(0,s[1].indexOf(","))); return new Date(day, month, year); } public static void main(String args[]){ Scanner sc = new Scanner(System.in); /* Scanner sc = null; try { sc = new Scanner(new FileInputStream("C:\\Users\\ddguo\\Desktop\\input.txt")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ int num = sc.nextInt(); sc.nextLine(); Main main = new Main(); main.initMonth(); int caseNum = 1; while(num-->0){ String start = sc.nextLine(); String end = sc.nextLine(); String res = "Case #"+caseNum+": "+main.coutNum(start, end); System.out.println(res); caseNum++; } sc.close(); } }
原文地址:http://blog.csdn.net/guorudi/article/details/45192309