题解 | 日期累加

日期累加

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

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<assert.h>
#include<iomanip>
using namespace std;

class Date {
public:
    // 友元仅保留输出(输入简化为直接读取,无需友元)
    friend ostream& operator<<(ostream& out, const Date& d);

    // 仅保留必要的构造函数(全缺省,适配题目输入)
    Date(int year = 1900, int month = 1, int day = 1) {
        _year = year;
        _month = month;
        _day = day;
    }

    // 核心:获取某月天数(含闰年判断)
    int GetMonthDay(int year, int month) const {
        assert(month > 0 && month < 13);
        static int days[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 days[month];
    }

    // 核心:日期+=天数(题目核心需求)
    Date& operator+=(int day) {
        if (day < 0) { // 兼容负数天数(等价于减)
            day = -day;
            _day -= day;
            while (_day <= 0) {
                --_month;
                if (_month == 0) {
                    --_year;
                    _month = 12;
                }
                _day += GetMonthDay(_year, _month);
            }
        } else {
            _day += day;
            while (_day > GetMonthDay(_year, _month)) {
                _day -= GetMonthDay(_year, _month);
                _month++;
                if (_month > 12) {
                    _year++;
                    _month = 1;
                }
            }
        }
        return *this;
    }

    // 合法性校验(可选,题目输入合法可注释)
    bool CheckDate() const {
        return _month >= 1 && _month <= 12 
               && _day >= 1 && _day <= GetMonthDay(_year, _month);
    }

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

// 输出格式:yyyy-mm-dd(补前导零)
ostream& operator<<(ostream& out, const Date& d) {
    out << setw(4) << setfill('0') << d._year << "-"
        << setw(2) << setfill('0') << d._month << "-"
        << setw(2) << setfill('0') << d._day;
    return out;
}

int main() {
    int m;
    cin >> m; // 读取样例数
    while (m--) {
        int year, month, day, add_days;
        cin >> year >> month >> day >> add_days;
        Date d(year, month, day);
        d += add_days; // 核心:日期累加
        cout << d << endl;
    }
    return 0;
}

全部评论

相关推荐

03-15 10:59
已编辑
美团_后端开发(实习员工)
爱写代码的菜code...:哎,自己当时拿到字节offer的时候也在感叹终于拿到了,自己当时最想去的企业就是字节,结果还是阴差阳错去了鹅厂。祝uu一切顺利!!!
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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