zoukankan      html  css  js  c++  java
  • 1185. 一周中的第几天『简单』

    题目来源于力扣(LeetCode

    一、题目

    1185. 一周中的第几天

    题目相关标签:数组

    提示:

    • 给出的日期一定是在 19712100 年之间的有效日期。

    二、解题思路

    1. 1971年1月1日为星期五为基准,最终计算得到给定日期与 1971年1月1日之间的天数

    2. 索引即天数 % 7,,返回 strs 字符串数组中对应索引上的字符串元素

    三、代码实现

    public static String dayOfTheWeek(int day, int month, int year) {
        int days = day;  // 月份的天数
        // 整除后的值即为数组索引上的元素
        String[] strs = {"Thursday", "Friday", "Saturday", "Sunday", "Monday",
                         "Tuesday", "Wednesday"};
        // 从1971年开始相加日期,加到指定日期 - 1 的年份
        for (int i = 1971; i < year; i++) {
            if (isLeapYear(i)) {
                // 闰年时加365 + 1
                days += 366;
            } else {
                // 平年加365
                days += 365;
            }
        }
        // 计算当前年的月份天数,从1月份到指定月份 - 1
        for (int i = 1; i < month; i++) {
            // 4,6,9,11 月份时加 30 天
            if (i == 4 || i == 6 || i == 9 || i == 11) {
                days += 30;
            } else if (i == 2) {
                // 2 月份时判断当前年是否闰年
                if (isLeapYear(year)) {
                    days += 29;
                } else {
                    days += 28;
                }
            } else {
                // 其余月份加 31 天
                days += 31;
            }
        }
        // 结果为 1 时 Friday,为 0 时 Thursday
        return strs[days % 7];
    }
    
    // 判断年份是否闰年
    public static boolean isLeapYear(int year) {
        // 年份能被4整除同时不能被100整除,2020 与 1900
        if (year % 4 == 0 && year % 100 != 0) {
            return true;
        }
        // 年份能被400整除,2000 与 1900
        if (year % 400 == 0) {
            return true;
        }
        return false;
    }
    

    四、执行用时

    五、部分测试用例

    public static void main(String[] args) {
        int day = 31, month = 8, year = 2019;  // output: "Saturday"
    //    int day = 18, month = 7, year = 1999;  // output: "Sunday"
    //    int day = 15, month = 8, year = 1993;  // output: "Sunday"
    
        String result = dayOfTheWeek(day, month, year);
        System.out.println(result);
    }
    
  • 相关阅读:
    Nagios HTTP WARNING: HTTP/1.1 403 Forbidden
    nagios监控的安装
    Linux里使用rz和sz命令
    Mariadb安装
    ubuntu16.04下载地址
    安装.msi格式安装包
    英文语法检测工具
    正确引用R及R包
    West world 西部世界
    Altered Carbon 碳变/副本
  • 原文地址:https://www.cnblogs.com/zhiyin1209/p/13173667.html
Copyright © 2011-2022 走看看