题解 | #日期差值#

日期差值

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

#include <iostream>
using namespace std;
class Date {
  public:
    //构造函数
    Date(int year, int month, int day)
        : _year(year)
        , _month(month)
        , _day(day)
        , _sum(1) //根据题目的说明,则初始化为1
        {
        //判日期的合法性
        if (!Invalid()) {
            cout << "输入的日期非法" << endl;
            exit(-1);
        }
    }
    //检查合法性
    bool Invalid() {
        if (_year < 1 
        || _month < 1 
        || _month > 12 
        || _day < 1 
        ||_day > GetMonthDays(_year, _month))
            return false;
        else
            return true;
    }
    //获取月份的天数
    int GetMonthDays(int year, int month) {
        static int monthdays[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 monthdays[month];
    }
    //运算符重载-
    Date operator-(Date d);
    //获取年份
    int GetYear() {
        return _year;
    }
    //获取日期差
    int GetSum() {
        return _sum;
    }
  private:
    int _year;
    int _month;
    int _day;
    int _sum;
};
//分割日期
Date DivideUp(int date) {
    int year = 0;
    int month = 0;
    int day = 0;
    year = date / 10000;
    month = (date - year * 10000) / 100;
    day = date - year * 10000 - month * 100;
    return Date(year, month, day);
}

//运算符重载-
Date Date::operator-(Date d) {
    while (_year != d._year) {
        _day -= 1;
        _sum++;
        while (_day <= 0) {
            --_month;
            if (_month == 0) {
                --_year;
                _month = 12;
            }
            _day += GetMonthDays(_year, _month);
        }
    }
    while (_month != d._month) {
        _day -= 1;
        _sum++;
        while (_day <= 0) {
            --_month;
            _day += GetMonthDays(_year, _month);
        }
    }
    while (_day != d._day) {
        _day--;
        _sum++;
    }
    return *this;
}

int main() {
    int date1 = 0;
    int date2 = 0;
    //cout << "请输入年月日:>" << endl;
    cin >> date1 >> date2;
    //日期分割
    Date d1 = DivideUp(date1);
    Date d2 = DivideUp(date2);
    //日期相减,大的减去小的
    if (d1.GetYear() <= d2.GetYear()) {
        Date d3 = d2 - d1;
        //日期差值
        cout << d3.GetSum() << endl;
    } else {
        Date d3 = d1 - d2;
        //日期差值
        cout << d3.GetSum() << endl;
    }
    return 0;
}

全部评论

相关推荐

牛客583549203号:腾讯还好,况且实习而已,实习生流动性很大,属于正常现象,记得和HR委婉解释
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务