日期差值 【codeup 1928】

日期差值 [codeup 1928]

题目描述

有两个日期,求两个日期之间的天数,如果两个日期是连续的我们规定他们之间的天数为两天。

输入

有多组数据,每组数据有两行,分别表示两个日期,形式为YYYYMMDD

输出

每组数据输出一行,即日期差值

样例输入

20130101
20130105

样例输出

5

解题思路
书上是一天一天地加,直到第二个日期。这循环未免太那啥了,我的思路是:如果两个日期不在同一年,则先数第一个日期到那一年结束还有多少天(先算那个月的剩余天数,再按月加天数),然后按年加天数,然后再加上第二个日期减去其所在年份的一月一号所得的天数;如果两个日期在同一年则,把这一年中两个日期已经过去的天数相减即可。当然最后得到的天数要加一,题目规定相邻两天的相隔天数为2.

代码

#include <cstdio>
using namespace std;

bool isLeap(int year){
	return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

int main(){
	//set every Month's days in array(Feb to be set later)
	int Days[13] = {-1, 31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
	int fstDate, secDate;
	while(scanf("%d%d",&fstDate,&secDate) != EOF){
		//exchange date if the former is bigger than the latter
		if(fstDate > secDate){
			int tmp = secDate;
			secDate = fstDate;
			fstDate = tmp;
		}
		
		//split Date into year, month, day
		int fstDay = fstDate % 100;
		int secDay = secDate % 100;
		int fstMonth = (fstDate / 100) % 100;
		int secMonth = (secDate / 100) % 100;
		int fstYear = fstDate / 10000;
		int secYear = secDate / 10000;

		int cnt = 0;//counting the difference between two days
		//two dates are not in the same year
		if(fstYear < secYear){
			Days[2] = isLeap(fstYear) ? 29 : 28;
			fstYear++;
			//count how many days remains in the firstMonth
			cnt += Days[fstMonth] - fstDay;
			//count how many days remains in the remaining 
			//Months of the year
			while(++fstMonth < 13)
				cnt += Days[fstMonth];
			//count how many days by years
			while(fstYear < secYear){
				cnt += isLeap(fstYear) ? 366 : 365;
				fstYear++;
			}
			//count how many days passed in the secYear
			Days[2] = isLeap(secYear) ? 29 : 28;
			for(int i = 1; i < secMonth; i++){
				cnt += Days[i];
			}
			cnt += secDay;
		}
		else{
			//two dates are in the same year
			//counting the difference by sub two passed days
			Days[2] = isLeap(secYear) ? 29 : 28;
			int days1 = 0, days2 = 0;
			for(int i = 1; i < fstMonth; i++)
				days1 += Days[i];
			for(int i = 1; i < secMonth; i++)
				days2 += Days[i];
			days1 += fstDay;
			days2 += secDay;
			cnt += days2 - days1;
		}
		//add one day according to the description of the problem
		printf("%d\n", cnt + 1);
	}
}
发布了30 篇原创文章 · 获赞 1 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/lvmy3/article/details/103823484