题解 | #字母统计#
日期差值
http://www.nowcoder.com/practice/ccb7383c76fc48d2bbc27a2a6319631c
/*
描述
有两个日期,求两个日期之间的天数,如果两个日期是连续的我们规定他们之间的天数为两天
输入描述:
有多组数据,每组数据有两行,分别表示两个日期,形式为YYYYMMDD
输出描述:
每组数据输出一行,即日期差值
*/
#include<iostream> using namespace std; bool isLeapYear(int year) { if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) return true; else return false; } int main() { int monthDays[2][12] = { {31,28,31,30,31,30,31,31,30,31,30,31}, // 非闰年月份的天数 {31,29,31,30,31,30,31,31,30,31,30,31} // 闰年月份的天数 }; char date1[9]; // note: 多申请一个空间给 \n char date2[9]; int y1, m1, d1, y2, m2, d2; int n1 = 0, n2 = 0; while (cin >> date1 >> date2) { n1 = n2 = 0; sscanf(date1, "%4d%2d%2d", &y1, &m1, &d1); sscanf(date2, "%4d%2d%2d", &y2, &m2, &d2); //cout << date1 << " " << date2 << endl; //cout << y1 << " " << m1 << " " << d1<<endl; //cout << y2 << " " << m2 << " " << d2<<endl; // year -> days for (int i = 0; i <= y1; ++i) n1 += isLeapYear(i) ? 366 : 365; for (int i = 0; i <= y2; ++i) n2 += isLeapYear(i) ? 366 : 365; // month -> days for (int j = 1; j < m1; ++j) n1 += monthDays[isLeapYear(y1)][j - 1]; for (int j = 1; j < m2; ++j) n2 += monthDays[isLeapYear(y2)][j - 1]; // days n1 += d1; n2 += d2; cout << abs(n1 - n2) + 1 << endl; } return 0; }