1154. 一年中的第几天『简单』

题目来源于力扣(LeetCode

一、题目

1154. 一年中的第几天

题目相关标签:数学

提示:

  • date.length == 10
  • date[4] == date[7] == '-',其他的 date[i] 都是数字。
  • date 表示的范围从 1900 年 1 月 1 日至 2019 年 12 月 31 日。

二、解题思路

2.1 Calendar 类

  1. 解析 date 字符串,得到年、月、日整型元素

  2. 调用 Calendar 类的 set 方法,完成日期的设置

  3. 调用 Calendar 类的 get 方法,通过 Calendar.DAY_OF_YEAR 属性获取到日期为一年中的第几天

2.2 数学计算

  1. 解析 date 字符串,得到年、月、日整型元素

  2. 日期相加,返回结果

三、代码实现

3.1 Calendar 类

public static int dayOfYear(String date) {
    String[] strs = date.split("-");
    int year = Integer.valueOf(strs[0]);
    int month = Integer.valueOf(strs[1]);
    int day = Integer.valueOf(strs[2]);
    if (month == 1) {
        return day;
    }
    Calendar calendar = Calendar.getInstance();
    // 调用 set 方法
    calendar.set(year, month - 1, day);
    // Calendar.DAY_OF_YEAR 获取到一年中的第几天
    return calendar.get(Calendar.DAY_OF_YEAR);
}

3.2 数学计算

public static int dayOfYear3(String date) {
    String[] strs = date.split("-");
    int year = Integer.valueOf(strs[0]);
    int month = Integer.valueOf(strs[1]);
    int day = Integer.valueOf(strs[2]);

    if (month == 1) {
        return day;
    }
    int days = day;
    // 非闰年时的月份天数
    int[] dayOfMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    int tempMonth = month - 1;  // 2019.1.9,结果为 9
	// 计算月份天数
    while (tempMonth > 0) {
        tempMonth -= 1;
        days += dayOfMonth[tempMonth];
    }
    if (month > 2) {
        // 闰年时需要加 1
        if ((year % 4 == 0 && year % 100 != 0)
            || (year % 100 == 0 && year % 400 == 0)) {
            days += 1;
        }
    }
    return days;
}

四、执行用时

4.1 Calendar 类

leetcode 中无法使用 Calendar API,执行报错

4.2 数学计算

五、部分测试用例

public static void main(String[] args) {
    String date = "2019-01-09";  // output: 9
//    String date = "2019-02-10";  // output: 41
//    String date = "2003-03-01";  // output: 60
//    String date = "2004-03-01";  // output: 61

    int result = dayOfYear(date);
    System.out.println(result);
}
posted @ 2020-06-21 19:46  知音12138  阅读(217)  评论(0编辑  收藏  举报