0%

Leetcode1185-dayOfTheWeek

Description

Given a date, return the corresponding day of the week for that date.

The input is given as three integers representing the day, month and year respectively.

Return the answer as one of the following values {“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”}.

Example

Example 1:

1
2
Input: day = 31, month = 8, year = 2019
Output: "Saturday"

Example 2:
1
2
Input: day = 18, month = 7, year = 1999
Output: "Sunday"

Example 3:
1
2
Input: day = 15, month = 8, year = 1993
Output: "Sunday"

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
// based on 1971-1-1 is Friday
public String dayOfTheWeek(int day, int month, int year) {
String[] week = new String[]{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
int[] months = new int[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int num = 0;
int i;
for (i = 1971; i < year; i++){
if ((i % 4 == 0 && i % 100 != 0) || i % 400 == 0) num += 366; //leap year
else num += 365;
}
if ((i % 4 == 0 && i % 100 != 0) || i % 400 == 0) months[1] = 29;
for (i = 0; i < month - 1; i++)
num += months[i];
num += day - 1;
return (week[(num + 5) % 7]);
}
}