题目 2571: 蓝桥杯2020年第十一届省赛真题-回文日期

这一题坑比较多,不注意的话就只能拿80到90分,有点坑。

思路暴力搜索即可。

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int monthd[13] = {31,28,31,30,31,31,30,31,30,31,30,31,29};//日期题目通用数组
int tf(int num){//判断是否回文数
	string s;
	while(num>0){
		s.push_back(num%10+'0');
		num/=10;
	}
	if(s[0]==s[2]&&s[2]==s[5]&&s[5]==s[7]&&s[1]==s[3]&&s[3]==s[4]&&s[4]==s[6]){//特殊回文数,1成立也代表0成立。
		return 1;
	}
	else if(s[0]==s[7]&&s[1]==s[6]&&s[2]==s[5]&&s[3]==s[4]){
		return 0;
	}
	else return -1;//都不是返回-1;
}
int main(){
	int N;
	cin>>N;
	int year = N/10000;
	int month = (N % 10000)/100;
	int day = N % 100;
	bool a = false,b = false;
	for(int i = year;i <= 10000; i++){//这里题目说明N<=8999但是答案不一定小于8999,要小心描述陷阱
		for(int j = 1;j <= 12; j++){//月份
			int k = monthd[j-1];//这里直接给天数赋值
			if(year%4==0)
				k = monthd[12];//闰年2月取29天
			for(int l = 1;l <= k; l++){
				if(a&&b){//如果都找到了,直接return 0;
				return 0;
				}
				int ymd = i * 10000 + j * 100 + l;
				if(ymd==N)continue;//起点不能算进内
				if(tf(ymd)==1&&!a){//找到特殊回文日期
					a = true;
					cout<<ymd<<endl;
					if(!b){//假如b还没找到,一并输出
						b = true;
						cout<<ymd<<endl;
					}
				}
				if(tf(ymd)==0&&!b){//普通的先找到
					b = true;
					cout<<ymd<<endl;
				}
			}
		}
	}
	return 0;
}

三个细节: 

1、找到的数不能等于起点。

2、有可能普通的没找到先找到特殊的,这时候需要再补一个条件,将特殊的再输出一遍。

3、题目描述年份的范围和题解不同,要是没确定好边界就会少分。

猜你喜欢

转载自blog.csdn.net/qq_63499305/article/details/129967347