1、🌟Acwing466. 回文日期
🌟思路
- 枚举每一个四位数年份
1000~9999,根据年份得出回文日期,然后判断该日期是否是非法日期,时间复杂度(104)
//构造回文日期
int reverse(int x)// 反转整数
{
int n = 0;
while (x) {
n = n \* 10 + x % 10;
x /= 10;
}
return n;
}
//string 处理
//用to\_string 将int 转 string
//判断是否为回文日期
bool flag = true;
string t = to\_string(i);
for(int j = 0; j <= 3; j++) {
if(t[j] != t[7-j]) {
flag = false;
break;
}
}
🌟C++代码
//466. 回文日期
#include <bits/stdc++.h>
using namespace std ;
int months[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 % 10000 / 100;
int day = date % 100;
if (!month || !day || month >= 13) {
return false;
}
if (month != 2 && months[month] < day) {//日期判断 都是 大于
return false;
}
if(month == 2) {
int leap = year % 400 == 0 || year % 100 != 0 && year % 4 == 0; //闰年
if(day > 28 + leap) {
return false;
}
}
return true;
}
int main () {
int date1, date2;
int ans = 0;
cin >> date1 >> date2;
for (int i = 1000; i < 10000; i ++) {//枚举所有四位日期
int date = i, x = i;
for (int i = 0; i < 4; i ++) {
date = date \* 10 + x % 10;
x /= 10;
}
if (date >= date1 && date <= date2 && check(date)) {
ans ++;
}
}
cout << ans << endl;
return 0;
}
2、🌟蓝桥杯2020年第十一届省赛真题-回文日期
🌟思路
这道题是真的坑,输出搞了好久。和上题思路一样,多了判断不ABAB型
🌟C++代码
//466. 回文日期
#include <bits/stdc++.h>
using namespace std ;
int months[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
bool check1(int date)
{
int year = date / 10000;
int month = date % 10000 / 100;
int day = date % 100;
if (!month || !day || month >= 13) {
return false;
}
if (month != 2 && months[month] < day) {
return false;
}
if(month == 2) {
int leap = year % 400 == 0 || year % 100 != 0 && year % 4 == 0;
if(day > 28 + leap) {
return false;
}
}
return true;
}
int check\_ABAB(int n) {
int a = n / 10000000 , b = n / 1000000 % 10 , c = n /100000 % 10 , d = n / 10000 % 10;
if(a == c && b == d && a != b) return true;
return false;
}
int main () {
int n;
cin >> n;
int falg = 1;
for (int i = n / 10000; i < 10000; i++) {
int x = i , t = i;
for(int j = 0;j < 4;j ++) {
x = x \* 10 + t % 10,t /= 10;
}
if(check1(x) && x > n && falg) {
printf("%d\n",x);
falg = 0;
}
if(check1(x) && check\_ABAB(x) && x > n) {
printf("%d\n",x);