题解 | 打印日期

打印日期

https://www.nowcoder.com/practice/b1f7a77416194fd3abd63737cdfcf82b

本题难点实际上是对“闰年”这一概念的理解。若非整百年份能被4整除则为闰年;整百年数当且仅当能被400整除时才是闰年

由于输入的日数仅可能是一年当中的第几天,所以闰年必然在1~366之间,平年的右端点减一。因此,只要划分出每过一个月对应一年中已经过了多少天作为确定月份的范围端点表,之后根据输入日数查表确定范围就可以了。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) {
            int year = in.nextInt();
            int dayCount = in.nextInt();

            // 判断闰年
            boolean lunarYearFlag = year % 4 == 0 && !(year % 100 == 0 && year % 400 != 0) ;
            int monthCount = 0;

            // 范围端点表
            int[] daysPassedLunar = new int[] {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366};
            int[] daysPassedNormal = new int[13];
            for (int i = 0; i <= 12; i++) {
                daysPassedNormal[i] = daysPassedLunar[i];
            }
            for (int i = 2; i <= 12; i++) {
                daysPassedNormal[i]--;
            }

            // 查表
            if (lunarYearFlag) {
                for (int i = 1; i <= 12; i++) {
                    if (dayCount > daysPassedLunar[i - 1] && dayCount <= daysPassedLunar[i]) {
                        monthCount = i;
                        dayCount -= daysPassedLunar[i - 1];
                        break;
                    }
                }
            } else {
                for (int i = 1; i <= 12; i++) {
                    if (dayCount > daysPassedNormal[i - 1] && dayCount <= daysPassedNormal[i]) {
                        monthCount = i;
                        dayCount -= daysPassedNormal[i - 1];
                        break;
                    }
                }
            }

            // 输出
            System.out.println(String.format("%04d", year) + "-" + String.format("%02d",
                               monthCount) + "-" + String.format("%02d", dayCount));
        }
    }
}
牛客题库练习笔记 文章被收录于专栏

有的时候心血来潮会来做题。做题就会有笔记。

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-04 14:35
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 12:11
点赞 评论 收藏
分享
积极的小学生不要香菜:你才沟通多少,没500不要说难
点赞 评论 收藏
分享
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 12:02
ssob上原来真有BOSS啊
硫蛋蛋:这种也是打工的,只不是是给写字楼房东打工
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务