直接穷举所有可能的日期,找符合条件的。
数据量很小,比如回文只需要穷举前四位,每位10个数,那也就是10^4而已。其实不用字符串也可以,但我觉得字符串比取余要简单一些,开始的时候是用to_string,但蓝桥杯官网的oj不给过,就换了stringstream流来实现数字转字符串。
#include<iostream>
#include<vector>
#include<algorithm>
#include<map>
#include<math.h>
#include<set>
#include<string>
#include<stack>
using namespace std;
#include<queue>
#include<sstream>
//判断是不是一个合法日期
bool isvalid(string s)
{
int year = atoi(s.substr(0, 4).c_str());
int month = atoi(s.substr(4, 2).c_str());
int day = atoi(s.substr(6, 2).c_str());
if (month > 12||month<=0)
{
return false;
}
if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 11) && day > 31)
{
return false;
}
if ((month == 4 || month == 6 || month == 9 || month == 12) && day > 30)
{
return false;
}
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
{
if (day > 29)
{
return false;
}
}
else
{
if (day > 28)
{
return false;
}
}
return true;
}
int main()
{
int n = 0;
cin >> n;
stringstream ss;
ss << n;
string str = ss.str();
string date = str;
int date2 = 0;
//穷举下一个回文日期,日期长度共八位,穷举四位剩下四位是前四位反过来
for (int i = 0; i <= 9; i++)
{
for (int j = 0; j <= 9; j++)
{
for (int k = 0; k <= 9; k++)
{
for (int t = 0; t <= 9; t++)
{
date2 = i * pow(10, 7) + j * pow(10, 6) + k * pow(10, 5) + t * pow(10, 4) + i + j * pow(10, 1) + k * pow(10, 2) + t * pow(10, 3);
stringstream ss1;
ss1 << date2;
string str = ss1.str();
if (date2 > n && isvalid(str))
{
goto A;
}
}
}
}
}
A:
//穷举ABABBABA,就两种变量,两个循环就行
int date3 = 0;
for (int i = 0; i <= 9; i++)
{
for (int j = 0; j <= 9; j++)
{
date3 = i * pow(10, 7) + j * pow(10, 6) + i * pow(10, 5) + j * pow(10, 4) + j * pow(10, 3) + i * pow(10, 2) + j * pow(10, 1) + i * pow(10, 0);
stringstream ss1;
ss1 << date3;
string str = ss1.str();
if (date3 > n && isvalid(str))
{
goto B;
}
}
}
B:
cout << date2 << endl;
cout << date3;
return 0;
}