class Solution {
public:
int monthdays(int year, int month){
if (month==2){
if ((year%4==0&&year%100!=0)||year%400==0){
return 29;
}
else{
return 28;
}
}
else if (month==1||month==3||month==5||month==7||month==8||month==10||month==12){
return 31;
}
else{
return 30;
}
}
int yeardays(int year){
int sum = 0;
for(int i=1;i<=12;i++){
sum += monthdays(year, i);
}
return sum;
}
// year1(2019.1.31)>=year2(2019.1.1)
// year1(2019.2.1)>=year2(2019.1.1)
// year1(2020.2.1)>=year2(2020.1.1)
int distance(int year, int month, int day, int minyear, int minmmonth, int minday){
int sum = 0;
for(int ii=minyear;ii<year;ii++){
sum += yeardays(ii);
}
for(int ii=minmmonth;ii<month;ii++){
sum += monthdays(year, ii);
}
sum += day-minday;
return sum;
}
int daysBetweenDates(string date1, string date2) {
int year1 = atoi(date1.substr(0,4).c_str());
int month1 = atoi(date1.substr(5,2).c_str());
int day1 = atoi(date1.substr(8,2).c_str());
int year2 = atoi(date2.substr(0,4).c_str());
int month2 = atoi(date2.substr(5,2).c_str());
int day2 = atoi(date2.substr(8,2).c_str());
int minyear = year1<year2?year1:year2;
int minmonth = 1;
int minday = 1;
int dis1 = distance(year1, month1, day1, minyear, minmonth, minday);
int dis2 = distance(year2, month2, day2, minyear, minmonth, minday);
return abs(dis1-dis2);
}
};
1360. Number of Days Between Two Dates
最新推荐文章于 2024-09-07 10:12:58 发布