1. 题目描述
有两个日期,求两个日期之间的天数,如果两个日期是连续的我们规定他们之间的天数为两天。
输入格式
输入包含多组测试数据。
每组数据占两行,分别表示两个日期,形式为 YYYYMMDD
。
输出格式
每组数据输出一行,即日期差值。
数据范围
年份范围 [1,9999], 保证输入日期合法。测试数据的组数不超过 100。
输入样例
20110412
20110422
输出样例
11
2. 我的尝试
模拟
#include <bits/stdc++.h>
using namespace std;
int a[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int toint(string s)
{
int res = 0;
for (auto & c : s)
res = res * 10 + c - '0';
return res;
}
class Date
{
public:
long long days;
Date(string s) {
int year = toint(s.substr(0, 4));
int month = toint(s.substr(4, 2));
int day = toint(s.substr(6, 2));
days = (year - 1) * 365;
for (int i = 1; i < month; i++) days += a[i - 1];
days += day;
if (is_run(year) && month > 2) days ++;
for (int i = 1; i < year; i++)
if (is_run(i)) days ++;
}
long long operator-(const Date &o){
return days > o.days ? days - o.days : o.days - days;
}
bool is_run(int year)
{
return (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0));
}
};
int main()
{
string day1, day2;
while(cin >> day1 >> day2)
{
Date d1(day1), d2(day2);
cout << d1 - d2 + 1 << endl;
}
return 0;
}