LeetCode Number of Days Between Two Dates

1360. Number of Days Between Two Dates

Write a program to count the number of days between two dates.

The two dates are given as strings, their format is YYYY-MM-DD as shown in the examples.

Example 1:

Input: date1 = "2019-06-29", date2 = "2019-06-30"
Output: 1

Example 2:

Input: date1 = "2020-01-15", date2 = "2019-12-31"
Output: 15

Constraints:

  • The given dates are valid dates between the years 1971 and 2100.

给定两个日期,计算这两个日期之间相隔的天数。

比较简单。如果年份和月份相同,直接天数作差。如果年份相同月份不同,则先把相隔的完整月份的天数算出来,存到part2;对于较早的日期,算出这个月还剩的天数part1;对于较晚的日期,算出这个月走过的天数part3;三者加起来。如果年份也不同,和上一种情况类似,先把间隔的完整年的天数算出来,寸到part2;对于较早的日期,算出这一年还剩的天数part2;对于较晚的日期,算出这一年走过的天数part3;三者加起来。

判断闰年的标准:是400的倍数;或者是4的倍数但不是100的倍数。

完整代码如下:

struct Date {
	int year;
	int month;
	int day;
	Date() {
		year = month = day = 0;
	}
	void parse(string date) {
		year = stoi(date.substr(0, 4));
		month = stoi(date.substr(5, 2));
		day = stoi(date.substr(8, 2));
	}
};
class Solution {
public:
	bool isRunYear(int year) {
		return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
	}
	int DaysInMonth(int m, int y) {
		switch (m) {
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			return 31;
		case 2:
			if (isRunYear(y))return 29;
			else return 28;
		default:
			return 30;
		}
	}

	int DaysInYear(int year) {
		if (isRunYear(year))return 366;
		else return 365;
	}

	int daysBetweenDates(string date1, string date2) {
		Date d1, d2;
		if (date1 < date2) {
			d1.parse(date1);
			d2.parse(date2);
		}
		else {
			d1.parse(date2);
			d2.parse(date1);
		}

		if (d1.year == d2.year && d1.month==d2.month) {
			return d2.day - d1.day;
		}
		else if (d1.year == d2.year) {
			int part1 = DaysInMonth(d1.month, d1.year) - d1.day;
			int part3 = d2.day;
			int part2 = 0;
			for (int m = d1.month + 1; m < d2.month; ++m) {
				part2 += DaysInMonth(m, d1.year);
			}
			return part1 + part2 + part3;
		}
		else {
			int part1 = DaysInMonth(d1.month, d1.year) - d1.day;
			for (int m = d1.month + 1; m <= 12; ++m) {
				part1 += DaysInMonth(m, d1.year);
			}
			int part2 = 0;
			for (int y = d1.year + 1; y < d2.year; ++y) {
				part2 += DaysInYear(y);
			}
			int part3 = d2.day;
			for (int m = 1; m < d2.month; ++m) {
				part3 += DaysInMonth(m, d2.year);
			}
			return part1 + part2 + part3;
		}
	}
};

本代码提交AC,用时4MS。

Leave a Reply

Your email address will not be published. Required fields are marked *