1185. The day of the week

Given a date, design an algorithm to determine which day of the week it corresponds to.

Enter three integers: day, month, and year, indicating the day, month, and year respectively.

The result you return must be one of these values {“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”}.

The constraint

The dates given must be valid between 1971 and 2100.


The sample

Example 1:

Input: day = 31, month = 8, year = 2019
Output: "Saturday"
Copy the code

Example 2:

Input: day = 18, month = 7, year = 1999
Output: "Sunday"
Copy the code

Example 3:

Input: day = 15, month = 8, year = 1993
Output: "Sunday"
Copy the code

Answer key

Important note:

  • 1970.12.31 is Thursday, which I think should be one of the conditions given by the title.
  • Leap years are defined as years that are multiples of 400 or years that are multiples of 4 instead of 100;
  • Leap years have one more day than ordinary years366Days;

WeekDay =(days+4)%7 is the day of the week (0 is Sunday).

Create an array weekDays=[“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”]

So weekDays[weekDay] is the final answer.

For example, if day =1, month =1, year = 1971, 1970.12.31 is days=1, then weekDay=(1+4)%7=5, i.e. WeekDays [5]=Friday.

So how to calculate the number of days between a given date and 1970.12.31? It can be divided into the following three steps:

  1. Calculation of specifiedyearIn 1971,The number of days between, or each year in a normal year365Day, or year if it’s a leap year366Days;
  2. Calculation of specifiedmonthTo theOn January 1The number of days between which1/3/5/7/8/10 / December31 days.On FebruaryCommon year is28 daysA leap year for29 days, the other months are30 days;
  3. Plus days of the monthday;

Days =(days+4)%7 (weekDay [weekDay])

code

public static String dayOfTheWeek(int day, int month, int year) {
    String[] weekDays = {"Sunday"."Monday"."Tuesday"."Wednesday"."Thursday"."Friday"."Saturday"};
    int days = 0;
    // 1. Count the number of days between year and 1971
    for (int y = 1971; y < year; y++) {
        days += isLeap(y) ? 366 : 365;
    }
    for (int m = 1; m < month; m++) {
        days += getMonthDays(m, year);
    }
    days += day;
    int weekDay = (days + 4) % 7;
    return weekDays[weekDay];
}

private static boolean isLeap(int year) {
    return year % 400= =0 || (year % 4= =0 && year % 100! =0);
}

private static int getMonthDays(int month, int year) {
    int[] monthDays = {31.28.31.30.31.30.31.31.30.31.30.31};
    int days = monthDays[month - 1];
    // If it is February and a leap year, an extra day is required
    return (month == 2 && isLeap(year)) ? days + 1 : days;
}
Copy the code