题解 | 日期差值
日期差值
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;
}
查看13道真题和解析
