1. Knowing 1/1/1971 is Friday(4 in array), sum up all days to today.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    int[][] monthDay = {
    {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
    {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
    };

    public String dayOfTheWeek(int day, int month, int year) {
    // 1/1/1971 Friday 4
    int res = 4;
    for (int i = 1971; i < year; ++i) {
    int k = isLeap(i);
    for (int j = 1; j <= 12; ++j) res += monthDay[k][j];
    }

    int k = isLeap(year);
    for (int i = 1; i < month; ++i) {
    res += monthDay[k][i];
    }

    res += day;
    res %= 7;

    String[] A = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
    return A[res];
    }

    public int isLeap(int year) {
    return ((year %4 == 0 && year % 100 != 0) || year %400 == 0) ? 1 : 0;
    }
  2. 坂本友彦:

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 d, int m, int y) {
// 2 = 3 + (28%7) - 1
static int t[] = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };

// before February
y -= m < 3;

int res = ( y + y / 4 - y / 100 + y / 400 + t[m - 1] + d) % 7;

if (res == 0) return "Sunday";
else if (res == 1) return "Monday";
else if (res == 2) return "Tuesday";
else if (res == 3) return "Wednesday";
else if (res == 4) return "Thursday";
else if (res == 5) return "Friday";
return "Saturday";
}
};