1. 问题描述:
在X星系的广袤空间中漂浮着许多X星人造"炸弹",用来作为宇宙中的路标。 每个炸弹都可以设定多少天之后爆炸。 比如:阿尔法炸弹2015年1月1日放置,定时为15天,则它在2015年1月16日爆炸。 有一个贝塔炸弹,a年b月c日放置,定时为n天,请你计算它爆炸的准确日期。
输入
输入存在多组数据,每组数据输入一行,每一行输入四个正整数a,b,c,n,输入保证日期在1000-01-01到2020-01-01之间,且日期合法。 n不超过1000
输出
请填写该日期,格式为 yyyy-mm-dd即4位年份2位月份2位日期。比如:2015-02-19 请严格按照格式书写。不能出现其它文字或符号。
样例输入
2015 1 1 15
2014 11 9 1000
样例输出
2015-01-16
2017-08-05
来源:http://oj.ecustacm.cn/problem.php?id=1251
2. 思路分析:
分析题目可以知道这道题目与之前蓝桥杯中跑步训练的题目是类似的,其实本质都是一样的,只是求解的问题不一样,这里需要计算的是从当前日期经过n天之后的日期,最简单而且比较快速和准确的方法是模拟一天一天翻日历的过程,翻日历的过程中其实可以记录很多的信息,比如年、月、日、星期等信息,根据题目要求解的是什么那么我们在翻日历的时候就记录什么
3. 代码如下:
from typing import List
# 判断是否是闰年
def isLeap(year: int):
return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
# 返回当前年份/月份对应的天数
def days(year: int, month: int, months: List[List[int]]):
return months[isLeap(year)][month - 1]
def solve(year: int, month: int, day: int, n: int):
# 声明二维列表的可以通过判断平年还是闰年取出对应年份/月份的天数
months = [[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]]
count = 0
while count < n:
# 对天数进行累加
day += 1
if day > days(year, month, months):
day = 1
month += 1
if month == 13:
month = 1
year += 1
# 当前的天数加1
count += 1
# 使用format函数格式化字符串, 使用format函数很方便规定以什么字符宽度来填充字符
return "{}-{:02d}-{:02d}".format(year, month, day)
if __name__ == '__main__':
while True:
year, month, day, n = map(int, input().split())
print(solve(year, month, day, n))