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

计算日期到天数转换

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            int year = in.nextInt();
            int month = in.nextInt();
            int day = in.nextInt();

            int days = 0;
            for (int x = 1; x < month; x ++) {
                days += daysOfMonth(year, x);
            }
            days += day;
            System.out.println(days);
        }
    }

    public static boolean isRunnian(int year) {
        return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
    }

    public static int daysOfMonth(int year, int month) {
        if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 ||
                month == 10 || month == 12) {
            return 31;
        }
        if (month == 4 || month == 6 || month == 9 || month == 11) {
            return 30;
        }
        if (month == 2) {
            return isRunnian(year) ? 29 : 28;
        }
        return 0;
    }
}

全部评论

相关推荐

球球别再泡了:坏,我单9要了14
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务