來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/day-of-the-week
題目描述:
給你一個日期胡本,請你設(shè)計一個算法來判斷它是對應(yīng)一周中的哪一天。
輸入為三個整數(shù):day气筋、month 和 year咱娶,分別表示日傻挂、月心剥、年院峡。
您返回的結(jié)果必須是這幾個值中的一個 {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}荣倾。
示例 1:
輸入:day = 31, month = 8, year = 2019
輸出:"Saturday"
示例 2:
輸入:day = 18, month = 7, year = 1999
輸出:"Sunday"
示例 3:
輸入:day = 15, month = 8, year = 1993
輸出:"Sunday"
思路:
- 1970年的最后一天是星期四
- 年 取模 4 如果等于0滨巴,則2月有29天
代碼實現(xiàn):
class Solution {
static String[] ss = new String[]{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
static int[] nums = new int[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
public String dayOfTheWeek(int day, int month, int year) {
int ans = 4;
for (int i = 1971; i < year; i++) {
boolean isLeap = (i % 4 == 0 && i % 100 != 0) || i % 400 == 0;
ans += isLeap ? 366 : 365;
}
for (int i = 1; i < month; i++) {
ans += nums[i - 1];
if (i == 2 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)) ans++;
}
ans += day;
return ss[ans % 7];
}
}