寝癖頭の解法

学習中の覚え書きを投稿、更新していきます。

paizaラーニング: 月の日数(C, C++, Python)

西暦y年m月の月の日数を計算して出力する問題と、その提出コードの解答例です。
paizaラーニングのレベルアップ問題集「日付セット」からの出典です。
paiza.jp
・問題
 西暦y年m月の月の日数を計算して表示してください。

 ただし、各月の日数は以下のように決まることに注意してください。
 4, 6, 9, 11月は30日
 2月は閏年ならば29日、そうでなければ28日
 それ以外の月は31日

 ただし、閏年は次のような年のことをいいます。
 西暦が4で割り切れる年は閏年
 ただし、100で割り切れる年は平年
 ただし、400で割り切れる年は閏年

・入力される値:
 整数yとmが次のように、スペース区切りで1行で入力されます。
   y m
 入力値最終行の末尾に改行が1つ入ります。
 文字列は標準入力から渡されます。

・期待する出力
 答えの数値を1行で出力してください。

・条件
 すべてのテストケースにおいて、以下の条件をみたします。
   1600≦y≦3000
   1≦m≦12

僕が作成、提出したコードは、以下のとおりです。

/*
C言語による月の日数
https://paiza.jp/works/mondai
提出コードの解答例
https://neguse-atama.hatenablog.com
*/
#include<stdio.h>
int main(void){
    int y,m;
    scanf("%d %d",&y,&m);
    if(m==2 && y%4==0){
        printf("29");
    }else if(m==2 && y%100==0){
        printf("28");
    }else if(m==2 && y%400!=0){
        printf("28");
    }else if(m==4 || m==6 || m==9 || m==11){
        printf("30");
    }else{
        printf("31");
    }
    putchar('\n');
    return 0;
}
/*
C++による月の日数
https://paiza.jp/works/mondai
提出コードの解答例
https://neguse-atama.hatenablog.com
*/
#include <iostream>
using namespace std;
int main(void){
    int y,m;
    cin>>y>>m;
    if(m==2 && y%4==0){
        cout<<29<<endl;
    }else if(m==2 && y%100==0){
        cout<<28<<endl;
    }else if(m==2 && y%400!=0){
        cout<<28<<endl;
    }else if(m==4 || m==6 || m==9 || m==11){
        cout<<30<<endl;
    }else{
        cout<<31<<endl;
    }
    return 0;
}

Pythonのバージョンは、3.x に対応します。

#Pythonによる月の日数
#https://paiza.jp/works/mondai
#提出コードの解答例1
#https://neguse-atama.hatenablog.com
y, m = map(int, input().split())

if m == 2 and y % 4 == 0:
    print(29)
elif m == 2 and y % 100 == 0:
    print(28)
elif m == 2 and y % 400 != 0:
    print(28)
elif m == 4 or m == 6 or m == 9 or m == 11:
    print(30)
else:
    print(31)

Pythonでは、標準モジュールのcalendarに閏年を判定する関数isleapが実装されています。

#Pythonによる月の日数
#https://paiza.jp/works/mondai
#提出コードの解答例2
#https://neguse-atama.hatenablog.com
import calendar

y, m = map(int, input().split())

if calendar.isleap(y) and m == 2:
    print(29)
elif m == 2:
    print(28)
elif m == 4 or m == 6 or m == 9 or m == 11:
    print(30)
else:
    print(31)

paizaラーニングのレベルアップ問題集については、ユーザー同士で解答を教え合ったり、コードを公開したりするのは自由としています。
また授業や研修、教材などにも利用できるそうです。