题解 | #日期差值#

日期差值

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;
}

全部评论

相关推荐

09-29 16:59
已编辑
门头沟学院 Java
牛客96609213...:疯狂背刺,之前还明确设置截止日期,还有笔试,现在一帮人卡在复筛,他反而一边开启扩招,还给扩招的免笔试,真服了,你好歹先把复筛中的给处理了再说
投递大疆等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务