题解 | #日期累加#

日期累加

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")

全部评论

相关推荐

预计下个星期就能开奖吧,哪位老哥来给个准信
华孝子爱信等:对接人上周说的是这周
点赞 评论 收藏
分享
10-28 14:42
门头沟学院 Java
watermelon1124:因为嵌入式炸了
点赞 评论 收藏
分享
孤寡孤寡的牛牛很热情:为什么我2本9硕投了很多,都是简历或者挂,难道那个恶心人的测评真的得认真做吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务