LeetCode 1360: Number of Days Between Two Dates Solution
Master LeetCode problem 1360 (Number of Days Between Two Dates), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
Problem Explanation
Explanation:
To solve this problem, we can follow these steps:
- Parse the input strings to extract year, month, and day for each date.
- Calculate the total number of days for each date by summing up days in years, months, and days considering leap years.
- Calculate the difference between the total days of the two dates.
Time complexity: O(1)
Space complexity: O(1)
:
Solution Code
class Solution {
public int daysBetweenDates(String date1, String date2) {
return Math.abs(daysFrom1971(date1) - daysFrom1971(date2));
}
private int daysFrom1971(String date) {
int[] daysInMonth = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
String[] s = date.split("-");
int year = Integer.parseInt(s[0]);
int month = Integer.parseInt(s[1]);
int day = Integer.parseInt(s[2]);
int days = day - 1;
for (int i = 1971; i < year; i++) {
days += isLeapYear(i) ? 366 : 365;
}
for (int i = 1; i < month; i++) {
days += i == 2 && isLeapYear(year) ? 29 : daysInMonth[i];
}
return days;
}
private boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1360 (Number of Days Between Two Dates)?
This page provides optimized solutions for LeetCode problem 1360 (Number of Days Between Two Dates) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1360 (Number of Days Between Two Dates)?
The time complexity for LeetCode 1360 (Number of Days Between Two Dates) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1360 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1360 in Java, C++, or Python.