第十一届蓝桥杯省赛C++ 试题G:回文日期【代码详细注释版】

代码:

/*
(year % 4 == 0 && year % 100) || (year % 400 == 0)
是闰年:
1.整除4但不整除100
2.整除400

闰年和平年的差别在第2月:
    闰年的第二月有29天,平年的第二月28天

*/
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
#define N 5
using namespace std;

int days[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};

int check_vaild(int n)
{
    int year = n / 10000 , month = n % 10000 / 100 , day = n % 100;

    if(month < 0 || month > 12)   return false;//月份超范围

    if(day < 0 || (day > days[month] && month != 2))    return false;//先不判断第二个月的天数是否超出范围

    //单独判断第二个月的天数:分为闰年和平年
    int x = 0;
    if(month == 2)
        x = year % 4 == 0 && year % 100 || year % 400 == 0;
    if(day > days[month] + x)   return false;

    return true;
}

int check_ABAB(int n)
{
    int a = n / 10000000 , b = n / 1000000 % 10 , c = n /100000 % 10 , d = n / 10000 % 10;
    if(a == c && b == d && a != b)  return true;
    return false;
}

int main()
{
    int n;
    scanf("%d",&n);
     /*不知道下一个回文日期的年份(即前四位数),
    就把前四位数作为一个整体枚举,枚举的时候同时把回文串拼接在后面存储在x里  
    */
    int falg = 1;
    for(int i = n / 10000;i < 100000;i ++)//i是前四位数
    {
        int x = i , t = i;
        for(int j = 0;j < 4;j ++)
            x = x*10 + t%10 , t /= 10;//2020 * 10 + (2020) % 10 = 20200 把t的最后一位数去掉
        if(check_vaild(x) && x > n && falg)
        {
            printf("%d\n",x);
            falg = 0;//找到下一个回文串后,标志结束
        }
        if(check_vaild(x) && check_ABAB(x) && x > n)
        {
            printf("%d\n",x);
            break;
        }
    }


    return 0;
}

 

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值