题解 | #日期差值#
日期差值
https://www.nowcoder.com/practice/ccb7383c76fc48d2bbc27a2a6319631c
#include <iostream> using namespace std; class Date { public: int GetMonthDay(int year, int month) { int array[13] = { 0, 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 array[month] + 1; } return array[month]; } Date(int year, int month, int day) { _year = year; _month = month; _day = day; } // <运算符重载 bool operator < (const Date& d) { if (_year < d._year) return true; else if ((_year == d._year) && (_month < d._month)) return true; else if (_day < d._day) return true; return false; } Date& operator+=(int day) { _day = _day + day; while (_day > GetMonthDay(_year, _month)) { _day -= GetMonthDay(_year, _month); _month++; if (_month > 12) { _year++; _month = 1; } } return *this; } Date& operator++() { *this += 1; return *this; } int operator-(const Date& d) { int day = 1; Date max = *this; Date min = d; if (*this < d) { max = d; min = *this; } while (min < max) { ++min; ++day; } return day; } private: int _year; int _month; int _day; }; int main() { int ayear,amonth,aday; int byear,bmonth,bday; scanf("%4d%2d%2d",&ayear,&amonth,&aday); scanf("%4d%2d%2d",&byear,&bmonth,&bday); Date d1(ayear,amonth,aday); Date d2(byear,bmonth,bday); int day = d1 - d2; cout << day << endl; } // 64 位输出请用 printf("%lld")