题解 | 日期差值

日期差值

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

#include <iostream>
using namespace std;



class Date {
  public:
    Date(int year = 1, int month = 1, int day = 1) {
        _year = year;
        _month = month;
        _day = day;
    }

    int GetMonthDay(int year, int month) {
        static int days[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;
        } else {
            return days[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;
    }


    Date& operator+(int days){
        _day += 1;
        if(_day > GetMonthDay(_year, _month)){
            _day = 1;
            _month += 1;
        }
        if(_month > 12){
            _year += 1;
            _month = 1;
        }
        return *this;
    }
  private:
    int _year;
    int _month;
    int _day;
};

int main() {
    int date1, date2;
    cin >> date1 >> date2;
    int year1 = date1 / 10000, month1 = date1 % 10000 / 100, day1 = date1 % 100;
    int year2 = date2 / 10000, month2 = date2 % 10000 / 100, day2 = date2 % 100;
    Date d1(year1, month1, day1);
    Date d2(year2, month2, day2);

    Date MaxDate = d1, MinDate = d2;
    if(d1 < d2){
        MaxDate = d2;
        MinDate = d1;
    }

    int res = 1;
    while(MinDate < MaxDate){
        res += 1;
        MinDate = MinDate + 1;
    }

    cout << res;
}

全部评论

相关推荐

03-10 11:23
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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