题解 | 日期差值
日期差值
https://www.nowcoder.com/practice/ccb7383c76fc48d2bbc27a2a6319631c
#include <iostream>
#include <cmath>
using namespace std;
int days[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int getMonthDays(int _year, int i) {
if ((_year % 4 == 0 && _year % 100 != 0) || (_year % 400 == 0)) {
if (i == 2) {
return 29;
}
}
return days[i];
}
long long dateToTotalDays(int date) {
int year = date / 10000;
int month = (date % 10000) / 100;
int day = date % 100;
long long total = 0;
for (int y = 1; y < year; ++y) {
total += ((y%4==0&&y%100!=0)||(y%400==0)) ? 366 : 365;
}
for (int m = 1; m < month; ++m) {
total += getMonthDays(year, m);
}
total += day;
return total;
}
int main() {
int date1, date2;
while (cin >> date1 >> date2) {
long long total1 = dateToTotalDays(date1);
long long total2 = dateToTotalDays(date2);
long long diff = abs(total1 - total2) + 1;
cout << diff << endl;
}
return 0;
}