问题 A: 日期差值
时间限制 : 1.000 sec 内存限制 : 32 MB
题目描述
有两个日期,求两个日期之间的天数,如果两个日期是连续的我们规定他们之间的天数为两天。
输入
有多组数据,每组数据有两行,分别表示两个日期,形式为YYYYMMDD
输出
每组数据输出一行,即日期差值
样例输入
20130101
20130105
样例输出
5
直接通过累加达到与第二个日期相符合的,如果左边日期大于右边日期,则需要交换位置
#include <iostream>
#include <algorithm>
using namespace std;
int a[2][13] = {
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};
int main() {
string n, m;
iostream::sync_with_stdio(false);
while (cin >> n >> m) {
if (n > m) {
swap(n, m);
}
int year = stoi(n.substr(0, 4));
int month = stoi(n.substr(4, 2));
int day = stoi(n.substr(6, 2));
int year1 = stoi(m.substr(0, 4));
int month1 = stoi(m.substr(4, 2));
int day1 = stoi(m.substr(6, 2));
int sum = 1;
while (year < year1 || month < month1 || day < day1) {
day++;
if (day == a[(year % 4 == 0) and (year % 100 != 0) || (year % 400 == 0)][month] + 1) {
month++;
day = 1;
}
if (month == 13) {
year++;
month = 1;
}
sum++;
}
cout << sum << endl;
}
return 0;
}