回文日期(枚举)

 要求输入一个八位整数N,输出要求第一个输出下一个回文日期,第二个表示下一个ABABBABA的回文日期

算法分析:

有多种枚举的方法,一种是直接从输入的整数开始,依次加一开始验证,知道符合输出要求。但是这种算法复杂度较高,所以比较好的方法就是从输入日期开始枚举年份,然后将其翻转得到y,两个拼接起来就是答案,在判断是否是ABABBABA型的就可以了。

#include<iostream>
#include<algorithm>
#include<iomanip>
#include<string>

using namespace std;
int D[13] = { -1,31,28,31,30,31,30,31,31,30,31,30,31 };  //12个月份,为了月份和数组下标统一加个-1.

bool check(int y)                 //判断是否为闰年
{
	if (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0))
	{
		return true;
	}
	return false;
}
bool ok(string s)    //判断是否为ABABBABA型回文数字
{
	if (s[0] == s[2] && s[0] == s[5] && s[0] == s[7] && s[1] == s[3] && s[1] == s[4] && s[1] == s[6])
		return true;
	return false;
}
int main()
{
	string S, ans1 = "", ans2 = "";
	cin >> S;
	for (int i = stoi(S.substr(0, 4)); ans1 =="" || ans2 == ""; i++)  //如果ans1和ans2有符合的就结束
	{
		string s = to_string(i), t = to_string(i);
		reverse(t.begin(), t.end());   //倒置函数
		s += t;                        //拼接起来
		if (s <= S)                     //如果小于输入就跳过
			continue;
		int y = stoi(s.substr(0, 4)), m = stoi(s.substr(4, 2)); //stoi变字符串为数字,substr是截图字符串函数
		int d = stoi(s.substr(6, 2));
		if (check(y))                      //闰年二月份改为29
			D[2] = 29;
		else
			D[2] = 28;
		if (m < 1 || m>12)          //不符合月份的跳过
			continue;  
		if (d < 1 || d> D[m])       //不符合天数的跳过
			continue;
		if (ans1 == "")               //符合就赋值
			ans1 = s;
		if (ok(s) && ans2== "")
			ans2= s;
	}
	cout << ans1 << "\n" << ans2 << endl;


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值