题解 | #计算日期到天数转换#

计算日期到天数转换

https://www.nowcoder.com/practice/769d45d455fe40b385ba32f97e7bcded

采用数组解法,把平年闰年都定义到两个数组中,然后根据判断取哪一个数组当作输入年的日历。从第 month - 1 月开始求天数和,然后再加上输入的日期,得到最终天数。

import java.util.Scanner;

public class Main {

    // 平年数组
    private static final int[] arr1 = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    // 闰年数组
    private static final int[] arr2 = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) {
            String s = in.nextLine();
            String[] sa = s.split(" ");
            // 拆分年月日
            int year  = Integer.parseInt(sa[0]);
            int month = Integer.parseInt(sa[1]);
            int days  = Integer.parseInt(sa[2]);
            // 判断是不是闰年,闰年用闰年数组,否则用平年数组
            if (isLeapYear(year)) {
                System.out.println(dayCount(arr2, month, days));
            } else {
                System.out.println(dayCount(arr1, month, days));
            }
        }
    }

    // 判断是否是闰年
    private static boolean isLeapYear(int year) {
        // 判断闰年的条件,能被 4 整除但是不能被 100 整除;或者能被 400 整除的,都是闰年
        return (year % 4 == 0 && !(year % 100 == 0)) || year % 400 == 0;
    }

    // 日期计算方法
    private static int dayCount(int[] cal, int month, int days) {
        int n = days;
        // 遍历日历数组,把他们的日期都叠加起来,注意叠加的是 month 之前的月,而不是 month 本月
        for (int i = 0; i < month - 1; i++) {
            n += cal[i];
        }
        return n;
    }
}

全部评论

相关推荐

FieldMatching:看成了猪头顾问,不好意思
点赞 评论 收藏
分享
xxxxOxo:该催就催,想要你的不会因为催就挂,催了就挂的是因为本来就要挂你
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务