Number of days#147

Number of days (Editorial)

Solution

General Idea :

We are asked to calculate the number of days between two calendar dates, including both the starting and ending days.

To do this, we:

  • Convert each date into the total number of days passed since year 1.

  • The difference between the two values gives the number of days between them.

  • Since the problem requires an inclusive count, we add 1 to the final result.

To correctly calculate the days:

  • We check whether a year is a leap year: [ Leap year if (y 400 = 0) or (y 4 = 0 and y 100 0) ]

  • February has 29 days in leap years, otherwise 28.

  • Other months follow their standard number of days.

For a given date (D, M, Y):

  • Add all days from years to Y-1.

  • Add all days from months to M-1 of year .

  • Add the day .

Let these totals be T_1 and T_2, then the answer is: [ |T_2 - T_1| + 1 ]

Time Complexity: where Y \leq 2100

#include <bits/stdc++.h>
using namespace std;

bool isLeap(int y) {
    if (y % 400 == 0) return true;
    if (y % 100 == 0) return false;
    return (y % 4 == 0);
}

int daysInMonth(int m, int y) {
    if (m == 2) return isLeap(y) ? 29 : 28;
    if (m == 4 || m == 6 || m == 9 || m == 11) return 30;
    return 31;
}

int getTotalDays(int d, int m, int y) {
    int days = 0;

    for (int i = 1; i < y; i++) {
        days += isLeap(i) ? 366 : 365;
    }

    for (int i = 1; i < m; i++) {
        days += daysInMonth(i, y);
    }

    days += d;
    return days;
}

int main() {
    int d1, m1, y1;
    int d2, m2, y2;

    cin >> d1 >> m1 >> y1;
    cin >> d2 >> m2 >> y2;

    int t1 = getTotalDays(d1, m1, y1);
    int t2 = getTotalDays(d2, m2, y2);

    cout << abs(t2 - t1) + 1;
    return 0;
}