HJ73 计算日期到天数转换

题目:

HJ73 计算日期到天数转换

题解:

模拟,将每个月的天数相加,需要注意闰年的2月多非闰年多一天。

闰年:能被4整除但是不能被100整数,或者能被400整除。

    private int getDay(int year, int month, int day) {
        int[] arr = new int[] {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        boolean leapYear = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;

        int count = 0;
        for (int i = 0; i < month-1; i++) {
            // 2月
            if (i == 1) {
                // 闰年
                if (leapYear) {
                    count += 29;
                } else {
                    count += arr[i];
                }
            } else {
                count += arr[i];
            }
        }

        count += day;
        return count;
    }

时间复杂度:O(n)

你可能感兴趣的:(华为机试,java,算法)