题解 | #计算日期到天数转换#
计算日期到天数转换
https://www.nowcoder.com/practice/769d45d455fe40b385ba32f97e7bcded
写一个日期类就可以了,不过我这个日期类没写全,够用就行
#include <iostream>
using namespace std;
class Date
{
public:
Date(int year = 0, int month = 0, int day = 0)
{
_year = year;
_month = month;
_day = day;
}
bool operator>(const Date& d) const
{
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==(const Date& d) const
{
if(this->_year == d._year
&& this->_month == d._month
&& this->_day == d._day)
return true;
else
return false;
}
bool operator!=(const Date& d) const
{
return !(*this == d);
}
bool operator<(const Date& d) const
{
return !(*this > d || *this == d);
}
Date& operator-=(int day)
{
if(day < 0)
{
*this += -day;
return *this;
}
_day -= day;
while(_day <= 0)
{
_month--;
if(_month == 0)
{
_month = 12;
_year--;
}
_day += GetMonthDays(_year, _month);
}
return *this;
}
Date& operator+=(int day)
{
if(day < 0)
{
*this -= -day;
return *this;
}
_day += day;
while(_day > GetMonthDays(_year, _month))
{
_day -= GetMonthDays(_year, _month);
_month++;
if(_month == 13)
{
_month = 1;
_year++;
}
}
return *this;
}
int GetMonthDays(int year, int month)
{
static int monthDays[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 monthDays[month];
}
Date& operator++()
{
*this += 1;
return *this;
}
int operator-(const Date& d) const
{
Date max = *this;
Date min = d;
int flag = 1;
int cnt = 0;
if(*this < d)
{
max = d;
min = *this;
flag = -1;
}
while(min != max)
{
++cnt;
++min;
}
return cnt * flag;
}
int TheDayOfYear()
{
return (*this - Date(_year, 1, 1)) + 1;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
int year, month, day;
while (cin >> year >> month >> day)
{
Date d(year, month, day);
cout << d.TheDayOfYear() << endl;
}
return 0;
}