判斷某年月日是當年的第幾天

題目描述:
輸入三個整數year,month,day分別表示當前年月日,輸出該天是當年的第幾天

思路:
* 由於只有十二個月,所以可以枚舉每個月的天數
* 需要單獨考慮的是當前年份是否是閏年&&當前月份是否大月2月,如果都滿足,則在總天數上+1

public class Main {
    public static void main(String args[]) {
        System.out.println(whichDay(2016,2,1));//爲當年第31+1 = 32天
        System.out.println(whichDay(2017,3,1));//爲當年第31+28+1 = 60天
        System.out.println(whichDay(2016,3,1));//爲當年第31+29+1 = 61天
    }
    /**
     * 由於只有十二個月,所以可以枚舉每個月的天數
     * 需要單獨考慮的是當前年份是否是閏年&&當前月份是否大月2月,如果都滿足,則在總天數上+1
     * @param year
     * @param month
     * @param day
     * @return
     */
    public static int whichDay(int year, int month, int day) {
        final int[] monthes = new int[]{31,28,31,30,31,30,31,31,30,31,30,31};
        int i = 0,num = 0;
        while(i < month - 1)
            num += monthes[i++];
        num += day;
        if(month < 3)
            return num;
        return num+isLeap(year);
    }

    /**
     * 判斷輸入的當前年份是否是閏年,是閏年則返回1,否則返回0;
     */
    public static int isLeap(int year) {
        if (year % 4 == 0 && year % 100 != 0)
            return 1;
        if (year % 400 == 0)
            return 1;
        else return 0;
    }
}

輸出如下:

32
60
61
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章