题解 | #日期差值#
日期差值
https://www.nowcoder.com/practice/ccb7383c76fc48d2bbc27a2a6319631c
#include <climits> #include <iostream> using namespace std; class Date { public: Date(int year, int month, int day) { _year = year; _month = month; _day = day; } int Days(int y, int m) { int arr[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; if (m == 2 ) if (y % 4 == 0 && y % 100 != 0 || y % 400 == 0) return 29; return arr[m]; } bool operator==(Date d) { if (this->_year == d._year && this->_month == d._month && this->_day == d._day) return true; return false; } Date operator+(int n) { Date tmp = *this; tmp._day += n; while (tmp._day > Days(tmp._year, tmp._month)) { tmp._day -= Days(tmp._year, tmp._month); tmp._month++; } while (tmp._month > 12) { tmp._month -= 12; tmp._year++; } return tmp; } Date& operator++() { *this = *this + 1; return *this; } bool operator>(Date d) { if (this->_year > d._year) return true; else if (this->_year == d._year && this->_month > d._month) return true; else if (this->_year == d._year && this->_month == d._month && this->_day > d._day) return true; else return false; } bool operator<(Date d) { if (*this > d || *this == d) return false; return true; } int operator-(const Date d) { if (*this < d) { // Date tmp = *this; int n = 0; while (!(tmp == d)) { ++tmp; n++; } return n; } Date tmp = d; int n = 0; while (!(tmp == *this)) { ++tmp; n++; } return n; } private: int _year; int _month; int _day; }; int main() { char ch1[9]; char ch2[9]; while (cin >> ch1 >> ch2) { // 注意 while 处理多个 case int year1, year2, month1, month2, day1, day2; sscanf(ch1, "%4d%2d%2d", &year1, &month1, &day1); sscanf(ch2, "%4d%2d%2d", &year2, &month2, &day2); Date d1(year1,month1,day1); Date d2(year2,month2,day2); int ret = d2-d1+1; cout << ret << endl; } } // 64 位输出请用 printf("%lld")