枚举
-
从给定日期开始枚举年份
年份确定(前四位数确定),若为回文数,则后四位数也是确定的。 -
得到枚举到的当前年份所确定的回文数,判断该回文数是否是有效日期。
参考文献
y总蓝桥杯辅导课
C++ 代码
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 10010;
int days[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
bool check(int date)
{
int year = date / 10000;
int month = date / 100 % 100;
int day = date % 100;
if(month == 0 || month > 12) return false;
if(day == 0) return false;
if(month != 2)
{
if(day > days[month]) return false;
}
else
{
int leap =(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
if(day > days[month] + leap) return false;
}
return true;
}
int main()
{
int n;
cin >> n;
int res1 = 0, res2 = 0;
for(int i = n / 10000; i < N; i ++)
{
int date = i, x = i;
for(int j = 0; j < 4; j ++)
{
date = date * 10 + x % 10;
x = x / 10;
}
if(check(date))
{
if(i % 100 == i / 100 && //ABAB满足条件
i % 10 != i / 10 % 10 && //A不等于B
res2 == 0 && //确保为第一个出现的符合条件的数
date != n //与输入数据不同
) res2 = date;
if(res1 == 0 && date != n) res1 = date;
}
}
cout << res1 << endl;
cout << res2 <<endl;
return 0;
}