A - Leap Year Editorial
by
toam
日付を扱う標準ライブラリを用いる解法
いくつかの言語では,標準ライブラリを用いてある年の日数を求めることができます.大きな方針としては以下の \(2\) つです.
- \(Y\) 年が閏年かどうかを判定する関数を用いる
- \(Y\) 年 \(1\) 月 \(1\) 日から \(Y+1\) 年 \(1\) 月 \(1\) 日(あるいは \(Y\) 年 \(12\) 月 \(31\) 日)までの日数を数える.
ここでは C++, Python, Go, Haskell について紹介します.
C++
C++20 から chrono
ライブラリに chrono::year
が追加されました.このクラスの中に閏年かどうかを判定する関数 is_leap
が含まれています.
#include <iostream>
#include <chrono>
using namespace std;
int main() {
int Y;
cin >> Y;
chrono::year year(Y);
if (year.is_leap()) {
cout << 366 <<endl;
} else {
cout << 365 <<endl;
}
return 0;
}
Python
calender
モジュールは日付に関連する機能があります.calendar.isleap
で閏年かどうかを bool 値で返します.
import calendar
Y = int(input())
if calendar.isleap(Y):
print(366)
else:
print(365)
datetime
モジュールも日付や時刻に関連する機能があります.datetime.date
で生成した \(2\) つの日付の間の日数を .days
を用いて求めることができます.
from datetime import date
Y = int(input())
print((date(Y + 1, 1, 1) - date(Y, 1, 1)).days)
Haskell
Data.Time.Calendar
モジュールで,日付や時間を扱うことができます.
isLeapYear
は閏年かどうかを Bool で返します.
import Data.Time.Calendar (isLeapYear)
year_days :: Bool -> Integer
year_days is_leap = if is_leap then 366 else 365
main = interact $ show . year_days . isLeapYear . (read :: String -> Integer)
fromGregorian
で Day 型の日付を生成し,diffDays
で \(2\) つの Day 型の日付の間の日数を計算することもできます.
import Data.Time.Calendar (fromGregorian, diffDays)
year_days :: Integer -> Integer
year_days y = diffDays (fromGregorian (y + 1) 1 1) (fromGregorian y 1 1)
main = interact $ show . year_days . (read :: String -> Integer)
Go
Go 言語の time
パッケージは,日付や時間を扱うことができます.time.Date
では年,月,日,時,分,秒,ナノ秒,およびタイムゾーンを指定することで time.Time
オブジェクトを生成します.YearDay
メソッドは,time.Time
オブジェクトの日付がその年の何日目であるかを返します.よって,この問題では \(Y\) 年 \(12\) 月 \(31\) 日目がその年の何日目かを求めればよいです.
package main
import (
"fmt"
"time"
)
func main() {
var Y int
fmt.Scan(&Y)
fmt.Println(time.Date(Y, 12, 31, 0, 0, 0, 0, time.UTC).YearDay())
}
この解説の執筆には MMNMM さんにご協力いただきました.
posted:
last update: