问题描述
有两个日期,求两个日期之间的天数,如果两个日期是连续的我们规定他们之间的天数为两天
输入描述:
有多组数据,每组数据有两行,分别表示两个日期,形式为YYYYMMDD
输出描述:
每组数据输出一行,即日期差值
示例
输入
20110412
20110422输出
11
C++实现
#include <bits/stdc++.h>
using namespace std;
int day_of_month[13][2] = {
{0, 0},
{31, 31},
{28, 29},
{31, 31},
{30, 30},
{31, 31},
{30, 30},
{31, 31},
{31, 31},
{30, 30},
{31, 31},
{30, 30},
{31, 31}
};
bool isLeap(int year) {
return (year % 400 == 0) || (year % 100 != 0 && year % 4 == 0);
}
struct Date {
int year;
int month;
int day;
Date(int time) {
year = time / 10000;
month = time % 10000 / 100;
day = time % 100;
}
void next() {
day++;
if(day == day_of_month[month][isLeap(year)] + 1) {
day = 1;
month++;
}
if(month == 13) {
month = 1;
year++;
}
}
bool operator <(const Date &date) {
int time1 = year * 10000 + month * 100 + day;
int time2 = date.year * 10000 + date.month * 100 + date.day;
return time1 < time2;
}
};
int main() {
int time1, time2;
while(scanf("%d%d", &time1, &time2) != EOF) {
if(time1 > time2) {
int temp = time1;
time1 = time2;
time2 = temp;
}
Date date1(time1);
Date date2(time2);
int ans = 1;
while(date1 < date2) {
date1.next();
ans++;
}
printf("%d\n", ans);
}
return 0;
}