题解 | #日期差值#
日期差值
https://www.nowcoder.com/practice/ccb7383c76fc48d2bbc27a2a6319631c
#include <iostream>
using namespace std;
class Date
{
friend istream& operator>> (istream& _in, Date& d);
public:
int GetMonthDay(int year, int month)
{
int DateArray[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;
}
return DateArray[month];
}
//d1 == d2
bool operator==(const Date& d)
{
if ((*this)._year == d._year &&
(*this)._month == d._month &&
(*this)._day == d._day)
{
return true;
}
return false;
}
bool operator!=(const Date& d)
{
return !(*this == d);
}
bool operator<(const Date& d)
{
if (_year < d._year)
{
return true;
}
else if (_year == d._year && _month < d._month)
{
return true;
}
else if (_year == d._year && _month == d._month && _day < d._day)
{
return true;
}
else
{
return false;
}
}
Date& operator+=(int day)
{
_day += day;
while (_day > GetMonthDay(_year, _month))
{
_day -= GetMonthDay(_year, _month);
++_month;
if (_month == 13)
{
_year += 1;
_month = 1;
}
}
return *this;
}
Date& operator++()
{
*this += 1;
return *this;
}
//
int operator-(const Date& d)
{
Date max = *this;
Date min = d;
if (*this < d)
{
max = d;
min = *this;
}
int n = 0;
while (max != min)
{
n++;
++min;
}
n++;
return n;
}
Date(int year = 1, int month = 1, int day = 1)
:_year(year)
, _month(month)
, _day(day)
{
}
private:
int _year;
int _month;
int _day;
};
//cin >> d1;
istream& operator>> (istream& _in, Date& d)
{
scanf("%4d %2d %2d", &(d._year), &(d._month), &(d._day));
return _in;
}
int main()
{
Date d1;
Date d2;
cin >> d1 >> d2;
cout << (d1 - d2) << endl;
return 0;
}
查看10道真题和解析