题解 | #日期差值#
日期差值
https://www.nowcoder.com/practice/ccb7383c76fc48d2bbc27a2a6319631c
#include <iostream>
using namespace std;
// 获取某年某月的天数
int GetMonthDay(int year, int month) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// 判断闰年
if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))) {
return 29;
}
return month_days[month - 1];
}
// 日期类
class Date {
public:
Date(int year = 0, int month = 0, int day = 0)
: _year(year), _month(month), _day(day) {}
friend Date GetDate(int n);
// 前置++操作符,用于日期自增
Date& operator++() {
_day++;
if (_day > GetMonthDay(_year, _month)) {
_day = 1;
_month++;
if (_month == 13) {
_month = 1;
_year++;
}
}
return *this;
}
// 计算两个日期之间的天数差
int operator-(const Date& d) const {
Date min_date = *this < d ? *this : d;
Date max_date = *this < d ? d : *this;
int days = 0;
while (min_date != max_date) {
++min_date;
days++;
}
return *this < d ? -days : days;
}
bool operator<(const Date& d) const {
if (_year != d._year) return _year < d._year;
if (_month != d._month) return _month < d._month;
return _day < d._day;
}
bool operator==(const Date& d) const {
return _year == d._year && _month == d._month && _day == d._day;
}
bool operator!=(const Date& d) const {
return !(*this == d);
}
private:
int _year;
int _month;
int _day;
};
// 从 YYYYMMDD 格式的整数中解析出 Date 对象
Date GetDate(int n) {
int year = n / 10000;
int month = (n / 100) % 100;
int day = n % 100;
return Date(year, month, day);
}
int main() {
int n1, n2;
while (cin >> n1 >> n2) {
Date d1 = GetDate(n1);
Date d2 = GetDate(n2);
cout << d2 - d1 + 1 << endl;
}
return 0;
}

