题解 | #日期累加#
日期累加
https://www.nowcoder.com/practice/eebb2983b7bf40408a1360efb33f9e5d
#include <iostream> using namespace std; class Date { friend ostream& operator<<(ostream& out, Date& d); public: Date(int year = 1, int month = 1, int day = 0) :_year(year) , _month(month) , _day(day) {} int GetMonthDay(int year, int month) { static int MonthdayArray[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 29; } else { return MonthdayArray[month]; } } bool operator<(Date& d) { if (_year < d._year) { return true; } else if (_year == d._year) { if (_month < d._month) { return true; } else if (_month == d._month) { if (_day < d._day) { return true; } } } return false; } bool operator==(Date& d) { return _year == d._year && _month == d._month && _day == d._day; } Date& operator++() { *this += 1; return *this; } Date operator+=(int day) { _day += day; while (_day > GetMonthDay(_year, _month)) { _day -= GetMonthDay(_year, _month); ++_month; if (_month == 13) { ++_year; _month = 1; } } return *this; } Date& operator+(int day) { *this += day; return *this; } private: int _year; int _month; int _day; }; ostream& operator<<(ostream& out, Date& d) { if (d._month < 10 && d._day < 10) { out << d._year << "-0" << d._month << "-0" << d._day << endl; } else if (d._month < 10 && d._day >= 10) { out << d._year << "-0" << d._month << "-" << d._day << endl; } else if (d._month >= 10 && d._day < 10) { out << d._year << "-" << d._month << "-0" << d._day << endl; } else { out << d._year << "-" << d._month << "-" << d._day << endl; } return out; } int main() { int n = 0; int year, month, day; int Accumulated_Days; cin >> n; while (n--) { // 注意 while 处理多个 case while (cin >> year >> month >> day >> Accumulated_Days) { Date d1(year, month, day); Date d2 = d1 + Accumulated_Days; cout << d1; } } } // 64 位输出请用 printf("%lld")