1. Topic
Please write a program to calculate the number of days interval between two dates.
Dates given a string format YYYY-MM-DD
, as shown in the example.
示例 1:
输入:date1 = "2019-06-29", date2 = "2019-06-30"
输出:1
示例 2:
输入:date1 = "2020-01-15", date2 = "2019-12-31"
输出:15
提示:
给定的日期是 1971 年到 2100 年之间的有效日期。
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/number-of-days-between-two-dates
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
2. Problem Solving
- Leap year judgment condition: divisible by 4, but can not be 100, 400 or be divisible
(year%4 == 0 && year%100 != 0) || year%400 == 0
It is a leap year
class Solution {
vector<int> month = {0,31,28,31,30,31,30,31,31,30,31,30,31};
public:
int daysBetweenDates(string date1, string date2) {
if(date1 == date2)
return 0;
if(date1 > date2)
swap(date1, date2);
int days = 0, y1, m1, d1, y2, m2, d2, i;
y1 = (date1[0]-'0')*1000+(date1[1]-'0')*100+(date1[2]-'0')*10+date1[3]-'0';
m1 = (date1[5]-'0')*10+date1[6]-'0';
d1 = (date1[8]-'0')*10+date1[9]-'0';
y2 = (date2[0]-'0')*1000+(date2[1]-'0')*100+(date2[2]-'0')*10+date2[3]-'0';
m2 = (date2[5]-'0')*10+date2[6]-'0';
d2 = (date2[8]-'0')*10+date2[9]-'0';
for(i = 1; i < m1; i++)
days -= month[i];
if(isleapyear(y1) && m1>2)
days--;//闰年2月29天
days -= d1;
for(i = y1; i < y2; ++i)
days += isleapyear(i) ? 366 : 365;
for(i = 1; i < m2; i++)
days += month[i];
if(isleapyear(y2) && m2>2)
days++;
days += d2;
return days;
}
bool isleapyear(int& year)
{
if((year%4 == 0 && year%100 != 0) || year%400 == 0)
return true;
return false;
}
};