案例二:回文日期

分析:

本题可以暴力枚举。有多种枚举方法。比较好的方法是:直接从输入日期中的年份开始枚举年份s,“再将其翻转得到t,那么s+t就是一个回文串。再对该串所对应的日期进行合法判断,如果是合法的日期,就得到第一个回文日期,如果是合法日期且是ABABBABA型,则是第一个ABABBABA型回文日期

本题涉及到以下知识
①字符串类string的使用:截取字符串;比较两个字符串的大小、是否相等;用运算符“+”实现字符串的拼接
②stoi函数:将一个字符串转换成一个整数,例如,由"2023"得到2023
③to_string函数:将一个整数转换成一个字符串
④reverse函数:将一个字符串逆序 

代码如下:

#include<bits/stdc++.h>
using namespace std;
//平年12个月的天数 
int D[13] = {-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
bool cheak(int y){
	if(y%400==0 or (y%4==0 and y%100!=0)) return true;
	else return false;
} 
bool ok(string s){  //判断ABABBABA型 
	if(s[0]==s[2] and s[0]==s[5] and s[0]==s[7] and
		s[1]==s[3] and s[1]==s[4] and s[1]==s[6]) return true;
	else return false;
}
int main(){
	string S, ans1 = "", ans2 = "";  //ans1,ans2:求得的2个答案
	cin >> S;  //输入的日期 
	for(int y = stoi(S.substr(0, 4));ans1=="" || ans2=="";y++){
		string s = to_string(y), t = to_string(y);
		reverse(t.begin(), t.end());  //将t逆序
		s += t;  //构造出来的回文日期
		if(s<=S) continue;
		int y1 = stoi(s.substr(0, 4)), m1 = stoi(s.substr(4, 2));
		int d1 = stoi(s.substr(6, 2));
		if(cheak(y1)) D[2] = 29;
		else D[2] = 23;
		if(m1<1 or m1>12) continue;
		if(d1<1 or d1>D[m1]) continue;
		if(ans1=="") ans1 = s; //第一个回文日期 
		//第一个ABABBABA型的回文日期
		if(ok(s) && ans2=="") ans2 = s;
	}
	cout << ans1 << endl;
	cout << ans2 << endl;
	return 0;
}
  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值