Skip to content

1185. Day of the Week 👎

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  string dayOfTheWeek(int day, int month, int year) {
    vector<string> week = {"Sunday",   "Monday", "Tuesday", "Wednesday",
                           "Thursday", "Friday", "Saturday"};
    vector<int> days = {
        31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    int count = 0;

    for (int i = 1971; i < year; ++i)
      count += i % 4 == 0 ? 366 : 365;
    for (int i = 0; i < month - 1; ++i)
      count += days[i];
    count += day;

    return week[(count + 4) % 7];
  }

 private:
  bool isLeapYear(int year) {
    return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public String dayOfTheWeek(int day, int month, int year) {
    String[] week = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
    int[] days = {31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    int count = 0;

    for (int i = 1971; i < year; ++i)
      count += i % 4 == 0 ? 366 : 365;
    for (int i = 0; i < month - 1; ++i)
      count += days[i];
    count += day;

    return week[(count + 4) % 7];
  }

  private boolean isLeapYear(int year) {
    return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
  def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
    def isLeapYear(year: int) -> bool:
      return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0

    week = ["Sunday", "Monday", "Tuesday",
            "Wednesday", "Thursday", "Friday", "Saturday"]
    days = [31, 29 if isLeapYear(
        year) else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    count = 0

    for i in range(1971, year):
      count += 366 if i % 4 == 0 else 365
    for i in range(month - 1):
      count += days[i]
    count += day

    return week[(count + 4) % 7]
Back to top