1. 程式人生 > >2015程式設計之美 2月29日(求閏年的個數)

2015程式設計之美 2月29日(求閏年的個數)

<span style="font-size:14px;">// 描述
// 給定兩個日期,計算這兩個日期之間有多少個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×10^9

// 樣例輸入
// 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

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class LeapYear
{
private:
	int year1;
	int month1;
	int day1;
	int year2;
	int month2;
	int day2;

public:
	int judgeMonth(string month)
	{
		if("January" == month) return 1;
		else if("February" == month) return 2;
		else if("March" == month) return 3;
		else if("April" == month) return 4;
		else if("May" == month) return 5;
		else if("June" == month) return 6;
		else if("July" == month) return 7;
		else if("August" == month) return 8;
		else if("September" == month) return 9;
		else if("October" == month) return 10;
		else if("November" == month) return 11;
		else return 12;
	}

	void init()
	{
		string monthStr;
		char sig;
		cin>>monthStr>>day1>>sig>>year1;
		month1 = judgeMonth(monthStr);
		cin>>monthStr>>day2>>sig>>year2;
		month2 = judgeMonth(monthStr);
	}

	int leapYearNum()
	{
		int lyNum = 0;
		int divide_4 = 0, divide_400 = 0, ndivide_100 = 0;
		if(month1<=1 || (month1<=2&&day1<=29))
			year1 -= 1;
		if(month2<=1 || (month2<=2&&day2<29))
			year2 -= 1;
		//從年份0年到開始年的閏年個數-從年分0年到結束年的閏年個數
		divide_400 = year2/400-year1/400;
		divide_4 = year2/4-year1/4;
		ndivide_100 = year2/100-year1/100;
		lyNum = divide_4 + divide_400 - ndivide_100;
		return lyNum;
	}
};

int main()
{
	int n = 0;
	LeapYear leapYear;
	while(cin>>n)
	{
		for(int i=1; i<=n; i++)
		{
			int lyNum = 0;
			leapYear.init();
			lyNum = leapYear.leapYearNum();
			cout<<"Case #"<<i<<": "<<lyNum<<endl;
		}
	}
	return 0;
}
</span>