Created
February 16, 2020 01:59
-
-
Save wushbin/7516fac11413abeeca899b566fe091a0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public String dayOfTheWeek(int day, int month, int year) { | |
int dayDiff = getDayDiff(day, month, year); | |
int currDayDiff = getDayDiff(9, 2, 2020); | |
int diff = dayDiff - currDayDiff; | |
int shift = diff % 7; | |
shift = (shift + 7) % 7; | |
String[] dict = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; | |
int currDayIndex = 0; | |
return dict[ currDayIndex + shift]; | |
} | |
private int getDayDiff(int day, int month, int year) { | |
int res = 0; | |
for (int y = 1971; y < year; y++) { | |
res += (checkLeapYear(y) ? 366 : 365); | |
} | |
boolean isLeap = checkLeapYear(year); | |
for (int m = 1; m < month; m++) { | |
res += getDayCount(isLeap, m); | |
} | |
res += day; | |
return res; | |
} | |
private int getDayCount(boolean isLeap, int month) { | |
if (isLeap && month == 2) { | |
return 29; | |
} else if (month == 2) { | |
return 28; | |
} | |
return ((month - 1) % 7) % 2 == 0 ? 31 : 30; | |
} | |
private boolean checkLeapYear(int year) { | |
return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment