1185. Day of the Week
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:
Example 2:
Example 3:
Constraints:
- The given dates are valid dates between the years
1971
and2100
.
Solution:
class Solution {
public String dayOfTheWeek(int day, int month, int year) {
String[] week = new String[]{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
int[] days = new int[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (isLeapYear(year)){
days[1] = 29;
}
int count = 0;
// Calculate total days from 1971 to the previous year
for (int i = 1971; i < year; i++){
if (i % 4 == 0){
count = count + 366;
}else{
count = count + 365;
}
}
// Add days from the beginning of the current year to the previous month
for (int i = 0; i < month - 1; i++){
count = days[i] + count;
}
// Add the days in the current month
count = count + day;
// // January 1, 1971, was a Friday, which is the 5th day in the week array
return week[(count + 4) % 7];
}
private boolean isLeapYear(int year){
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}
}