蓝桥杯——历届试题 回文日期-python

在这里插入图片描述

思路:每年都只有一个回文串例如1234年 就是12344321,所以根据前4位年份去构建对应的回文串,判断月份、日份是否在合法范围内即可。ABABBABA型同理只有一个,可以根据前2位构建这种类型的回文串。

n=int(input())+1
n1=n
#用字典存储每个月对应的天数   xx为闰年时2月的天数
dict={"01":31,"02":28,"03":31,"04":30,"05":31,"06":30,"07":31,"08":31,"09":30,"10":31,"11":30,"12":31,"xx":29}
while(1):
    s1=str(n)
    s2=str(int(n/10000))+s1[3]+s1[2]+s1[1]+s1[0]        #构建最近的回文数
    temp=s2[4]+s2[5]        #计算月份
    year=int(s2[0]+s2[1]+s2[2]+s2[3])
    if ((year%4==0 and year%100!=0) or year%400==0) and temp=="02":   #将闰年的2月月份改为xx
        temp="xx"
    if temp not in dict.keys():    #判断月份是否在字典中
        n+=10000
        continue
    else:
        if dict.get(temp)<int(s2[6]+s2[7]):   #判断对应月份的日期是否超过最大限度
            n+=10000
            continue
        else:
            print(s2)
            break


s1 = str(n1)
if(s1[2]>s1[0]):    #如果初始为12340123   则直接构建的话  应该是12211221<12340123  所以提前把第二位+1 13311331符合AB型条件
    n1 += 1000000
while(1):
    s1 = str(n1)
    s2 = str(int(n1 / 1000000)) + s1[0] + s1[1] + s1[1] + s1[0] + s1[1] + s1[0]
    temp = s2[4] + s2[5]
    year = int(s2[0] + s2[1] + s2[2] + s2[3])
    if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
        temp = "xx"
    if temp not in dict.keys():
        n1 += 1000000
        continue
    else:
        if dict.get(temp) < int(s2[6] + s2[7]):
            n1 += 1000000
            continue
        else:
            print(s2)
            break

版权声明:本文为qq_40280704原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。