Formatted question description: https://leetcode.ca/all/1185.html

# 1185. Day of the Week (Easy)

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 1:

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


Example 2:

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


Example 3:

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


Constraints:

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

Companies:
United Health Group

Related Topics:
Array

## Solution 1.

Compute difference between the date and 1971/1/1 which is Friday.

When the input is exactly 1971/1/1, the d + day will be 1. To get Friday, we need to shift it by 4.

// OJ: https://leetcode.com/problems/day-of-the-week/

// Time: O(1)
// Space: O(1)
class Solution {
private:
bool isLeapYear(int y) {
return y % 4 == 0 && (y % 100 != 0 || y % 400 == 0);
}
string dates = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
public:
string dayOfTheWeek(int day, int month, int year) { // Compare it with 1971/1/1 (Friday)
int d = 0;
for (int y = 1971; y < year; ++y) d += 365 + (isLeapYear(y) ? 1 : 0);
for (int m = 1; m < month; ++m) {
if (m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10) d += 31;
else if (m == 2) d += 28 + (isLeapYear(year) ? 1 : 0);
else d += 30;
}
return dates[(d + day + 4) % 7];
}
};


Java

class Solution {
public String dayOfTheWeek(int day, int month, int year) {
final String[] DAYS = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
int dayIndex = getDayIndex(day, month, year);
return DAYS[dayIndex];
}

public int getDayIndex(int day, int month, int year) {
if (month < 3) {
month += 12;
year--;
}
int century = year / 100, year2 = year % 100;
int index = year2 + year2 / 4 + century / 4 - 2 * century + 26 * (month + 1) / 10 + day - 1;
index %= 7;
if (index < 0)
index += 7;
return index;
}
}