Problem 1185. Day of the Week
Java Doomsday Algorithm
The algorithm was devised by John Conway in 1973. It is simple enough that it can be computed mentally. Conway could usually give the correct answer in under two seconds.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 class Solution { public String dayOfTheWeek (int day, int month, int year) { String s = "" ; int t[] = {0 , 3 , 2 , 5 , 0 , 3 , 5 , 1 , 4 , 6 , 2 , 4 }; if (month < 3 ) year -= 1 ; int i = (year + year/4 - year/100 + year/400 + t[month-1 ] + day) % 7 ; switch (i) { case 1 : s = "Monday" ; break ; case 2 : s = "Tuesday" ; break ; case 3 : s = "Wednesday" ; break ; case 4 : s = "Thursday" ; break ; case 5 : s = "Friday" ; break ; case 6 : s = "Saturday" ; break ; case 0 : case 7 : s = "Sunday" ; break ; default : ; } return s; } }
Submission Detail
39 / 39 test cases passed.
Runtime: 0 ms, faster than 100.00% of Java online submissions for Day of the Week.
Memory Usage: 37 MB, less than 100.00% of Java online submissions for Day of the Week.
jdk8 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import java.time.LocalDate;class Solution { public String dayOfTheWeek (int day, int month, int year) { String s = "" ; LocalDate d = LocalDate.of(year, month, day); switch (d.getDayOfWeek().getValue()) { case 1 : s = "Monday" ; break ; case 2 : s = "Tuesday" ; break ; case 3 : s = "Wednesday" ; break ; case 4 : s = "Thursday" ; break ; case 5 : s = "Friday" ; break ; case 6 : s = "Saturday" ; break ; case 7 : s = "Sunday" ; break ; default : ; } return s; } }
Submission Detail
39 / 39 test cases passed.
Runtime: 1 ms, faster than 26.65% of Java online submissions for Day of the Week.
Memory Usage: 37.2 MB, less than 100.00% of Java online submissions for Day of the Week.
Resources