0
0

More than 1 year has passed since last update.

【LeetCode】アルゴリズム体操 1154. Day of the Year

Posted at

LeetCode - Day of the Year

問題文

Given a string date representing a Gregorian calendar date formatted as YYYY-MM-DD, return the day number of the year.

だいたいの日本語訳

引数:String date
戻り値:int型の日数

「YYYY-MM-DD」の形でString型の日付を渡すから、その年の何日目かを計算しておくれやす。

解答

Solution.java
class Solution {
    public int dayOfYear(String date) {
        int[] days = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        int year = Integer.parseInt(date.substring(0, 4));
        int month = Integer.parseInt(date.substring(5, 7));
        int day = Integer.parseInt(date.substring(8, 10));
        // うるう年かつ3月以降の場合:1、その他:0
        int ans = year % 4 == 0 && month > 2 ? 1 : 0;

        for (int i = 0; i < month; i++) {
            ans += days[i];
        }

        ans += day;
        return ans;
    }
}

実行結果

Title RunTime Memory
解答 8ms 39.5MB

ひとこと

うるう年は4年ごと!かつ3月以降なのを忘れずに!うるう年と聞くと「流星の絆」を思い出します。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0