题解 | #日期差值#
日期差值
https://www.nowcoder.com/practice/ccb7383c76fc48d2bbc27a2a6319631c
#include <iostream>
#include <algorithm>
using namespace std;
class Date {
public:
Date(int year, int month, int day)
: _year(year), _month(month), _day(day) {}
bool operator==(const Date& d) const {
return _year == d._year && _month == d._month && _day == d._day;
}
bool operator<(const Date& d) const {
if (_year < d._year) return true;
if (_year == d._year && _month < d._month) return true;
if (_year == d._year && _month == d._month && _day < d._day) return true;
return false;
}
int GetMonthDay(int year, int month) const {
static int MonthArr[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (month == 2 && (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)))
return 29;
return MonthArr[month];
}
Date& operator--() {
_day--;
if (_day == 0) {
_month--;
if (_month == 0) {
_year--;
_month = 12;
}
_day = GetMonthDay(_year, _month);
}
return *this;
}
bool is_leapyear(int year) const {
return (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0));
}
int operator-(const Date& d)
{
Date max = *this;
Date min = d;
if (max < min) {
max = d;
min = *this;
}
int count = 0;
while (!(max._day == 1 && max._month == 1)) {
--max;
++count;
}
while (!(min._day == 1 && min._month == 1)) {
--min;
--count;
}
while (min._year < max._year) {
count += is_leapyear(min._year) ? 366 : 365;
++min._year;
}
return abs(count);
}
private:
int _year;
int _month;
int _day;
};
int main() {
int year1, month1, day1, year2, month2, day2;
while (scanf("%4d%2d%2d %4d%2d%2d", &year1, &month1, &day1, &year2, &month2, &day2) != EOF) {
Date d1(year1, month1, day1);
Date d2(year2, month2, day2);
int ret = d1 - d2 +1 ;
cout << ret << endl;
}
return 0;
}
顺丰集团工作强度 379人发布