题解 | #日期累加#

日期累加

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

#include <climits>
#include <iostream>
using namespace std;

class Date
{
protected:
    friend ostream&operator<<(ostream&out,const Date&d);
public:
    Date(int year ,int month,int day);
    
    Date operator+(int n);
    int GetMonthDay(int year,int month);
private:
    int _year;
    int _month;
    int _day;
};
Date::Date(int year ,int month,int day)
    :_day(day)
    ,_month(month)
    ,_year(year)
    {}
ostream&operator<<(ostream&out,const Date&d)
{
    if(d._month<10&&d._day<10)
        out << d._year << "-" <<0<< d._month << "-" <<0<< d._day;
    else if(d._month>=10&&d._day<10)
        out << d._year << "-" << d._month << "-" <<0<< d._day;
    else if(d._month<10&&d._day>=10)
        out << d._year << "-" <<0<< d._month << "-" << d._day;
    else
        out << d._year << "-" << d._month << "-" << d._day;
    return out;
    
}

Date Date::operator+(int n)//日期类的赋值重载加号
{
    int year=_year;
    int month=_month;
    int day=_day;
    int days=GetMonthDay(year,month);//获取当月的天数

    while(day+n>days)//如果加起来的天数大于当月底的天数的话我们就进行操作
    {
        month++;
        if(month>12)//变成了次年的1月了
        {
            year++;
            month=1;
        }
        n-=days;//减去当月的天数
        days=GetMonthDay(year, month);//获取当月的天数
    }
    //经过循环处理了的天数就变成个位数了
    day+=n;
    return Date(year,month,day);


    
}

int Date::GetMonthDay(int year, int month)
{
    static int days[13]={0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    int day=days[month];
    if(month==2&&((year%4==0&&year%100!=0)||(year%400==0)))
    {
        day+=1;//那么就是29天了
    }
    return day;
}

int main()
{
    int count=0;
    int year=0,month=0,day=0;
    int n=0;
    cin>>count;
    for(int cur=0;cur<count;cur++)
    {
        cin>>year>>month>>day>>n;
        Date d(year,month,day);
        Date d1=d+n;//加之后的天数
        cout<<d1<<endl;
    }
    return 0;
}

    

全部评论

相关推荐

不愿透露姓名的神秘牛友
10-05 10:13
已编辑
HHHHaos:让这些老登来现在秋招一下,简历都过不去
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务