题解 | #日期差值#

日期差值

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

#include <climits>
#include <iostream>
using namespace std;
class Date {
  public:
    Date() {
        cin >> _year;
        _day = _year % 100;
        _year /= 100;
        _month = _year % 100;
        _year /= 100;
    }
    int Get_MonthDay(int year, int month)const { //获取某年某月的天数
        static int array[13] = { -1, 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 array[month];
    }
    bool operator>(const Date& d)const {
        if (_year > d._year) {
            return true;
        } else if (_year == d._year) {
            if (_month > d._month) {
                return true;
            } else if (_month == d._month) {
                return _day > d._day;
            }
        }
        return false;
    }
    bool operator==(const Date& d)const {
        return _year == d._year
               && _month == d._month
               && _day == d._day;
    }
    bool operator!=(const Date& d)const
    {
        return !(*this == d);
    }
    Date& operator++()
    {
        if(++_day > Get_MonthDay(_year, _month))
        {
            if(_month == 12)
            {
                ++_year;
                _month = 1;
            }
            else 
            {
                ++_month;
            }
            _day = 1; 
        }
        return *this;
    }
    int operator-(const Date& d)const {
        Date max = *this;
        Date min = d;
        int count = 1;
        if(!(*this > d))
        {
            Date tmp = max;
            max = min;
            min = tmp;
        }
        while(min != max)
        {
            ++min;
            ++count;
        }
        return count;
    }
  private:
    int _year;
    int _month;
    int _day;
};
int main() {
    Date d1;
    Date d2;
    cout << d1-d2 << endl;
    return 0;
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-08 17:10
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-07 13:47
机械打工仔:你自己匿名可以,这么好的公司就别给它匿名了
点赞 评论 收藏
分享
程序员小白条:找的太晚,别人都是大三实习,然后大四秋招春招的,你大四下了才去实习,晚1年
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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