题解 | #日期累加#

日期累加

https://www.nowcoder.com/practice/eebb2983b7bf40408a1360efb33f9e5d

#include <fstream>
#include <iostream>
#include <ostream>
using namespace std;

int GetMonthDay(int y, int m)
{
    int month[] = { 0, 31, 28, 31, 30, 31, 30, 31,31, 30, 31, 30, 31 };
    if (m == 2 && ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0))
        return 29;
    return month[m];
}

class Date
{
public:
    Date(int year = 0, int month = 0, int day = 0)
        :_year(year),
        _month(month),
        _day(day)
    {}

    friend Date GetDate(int n);
    friend ostream & operator<<(ostream & _cout,const Date& d);

    Date& operator++()
    {
        _day++;
        if (_day > GetMonthDay(_year, _month))
        {
            _month++;
            _day = 1;
            if (_month == 13)
            {
                _month = 1;
                _year++;
            }
        }
        return *this;
    }

    Date operator+(int n)
    {
        Date tmp =*this;
        while(n--)
        {
            ++tmp;
        }
       return tmp;
    }

private:
    int _year;
    int _month;
    int _day;
};


ostream & operator<<(ostream & _cout,const Date &d1)
{
    if(d1._month<10&&d1._day<10)
    {
        _cout << d1._year << "-" << 0 <<d1._month << "-" << 0<<d1._day ; 
    }
    else if(d1._month<10&&d1._day>=10){
        _cout << d1._year << "-" << 0 <<d1._month << "-" << d1._day ; 
    }
    else if(d1._month>=10&&d1._day<10)
    {
        _cout << d1._year << "-" <<d1._month << "-" << 0<<d1._day ; 
    }
    else if(d1._month>=10&&d1._day>=10)
    {
        _cout << d1._year << "-" <<d1._month << "-" <<d1._day ; 
    }
    return _cout;
}


int main() {
    int n1, n2;
    int m;
    cin>>m;
    while(m--)
    {
        int n;
        int year,month,day;
        cin>>year>>month>>day>>n;
        Date d(year,month,day);
        cout<<(d+n)<<endl;
    }
}

全部评论

相关推荐

11-09 01:22
已编辑
东南大学 Java
高级特工穿山甲:羡慕,我秋招有家企业在茶馆组织线下面试,约我过去“喝茶详谈”😢结果我去了发现原来是人家喝茶我看着
点赞 评论 收藏
分享
10-14 10:56
已编辑
长沙学院 嵌入式软件开发
痴心的00后拿到了ssp:hr面挂了,无所谓了反正不去😃
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务