《算法笔记》3.4小节——入门模拟->日期处理
问题 A: 日期差值
题目
题目描述
有两个日期,求两个日期之间的天数,如果两个日期是连续的我们规定他们之间的天数为两天。
输入
有多组数据,每组数据有两行,分别表示两个日期,形式为 YYYYMMDD
输出
每组数据输出一行,即日期差值
样例输入
1 |
|
样例输出
1 |
|
题解
思路
几个注意事项:
为了方便我们使用一个二维数组
math[13][2]
存放每月的天数比较方便,需要分平年(一维)与闰年(二维);第一个日期大于第二个日期需要交换;
为了节省时间,可以先对年份进行判断
计算日期的差值,需要注意的是要判断一下闰年。
代码
1 |
|
问题 B: Day of Week
问题 C: 打印日期
题目
题目描述
给出年分m和一年中的第n天,算出第n天是几月几号。
输入
输入包括两个整数y(1<=y<=3000),n(1<=n<=366)。
输出
可能有多组测试数据,对于每组数据,按 yyyy-mm-dd的格式将输入中对应的日期打印出来。
样例输入 Copy
1 |
|
样例输出 Copy
1 |
|
题解
思路
这题不是很复杂,具体来说就是:
- 年份正常不需要变化,只有特殊情况:平年 366 天需要年数 +1,月份归 0 ;
- 正常计算思路为:
- 先找到最后一天所在的月:月份的天数累加,直到超过输入的值,然后需要退一步循环;
- 输出,
该天的值 = 输入的值 - 上一步累加的天数
;此时需要控制格式输出%0xd
;
代码
1 |
|
问题D:日期类
题目
题目描述
编写一个日期类,要求按xxxx-xx-xx
的格式输出日期,实现加一天的操作。
输入
输入第一行表示测试用例的个数 m,接下来 m 行每行有 3 个用空格隔开的整数,分别表示年月日。测试数据不会有闰年。
输出
输出 m
行。按xxxx-xx-xx
的格式输出,表示输入日期的后一天的日期。
样例输入
1 |
|
样例输出
1 |
|
提示
注意个位数日期前面要有 0。
题解
思路
- 第一行的输入变量
count
作为循环条件; - 判断当前天数是否是当前月的最后一天,如果是,则天数置为 1,月份加 1;否则天数加 1,此时需要判断平闰年;
- 如果月份 + 1 之后变为 13,则月份置为 1,年份加 1。
代码
1 |
|
问题E:日期类加
题目
题目描述
设计一个程序能计算一个日期加上若干天后是什么日期。
输入
输入第一行表示样例个数 m,接下来m行每行四个整数分别表示年月日和累加的天数。
输出
输出 m 行,每行按 yyyy-mm-dd 的个数输出。
样例输入
1 |
|
样例输出
1 |
|
题解
思路
不要想什么套路,最简单的做法就是最好的,只要提交不爆时间,一直leap--
就好。
代码
1 |
|
《算法笔记》3.4小节——入门模拟->日期处理
https://excelius.xyz/《算法笔记》3-4小节——入门模拟-日期处理/