类似题 - 466. 回文日期
写法2,先生成回文日期,再判断合不合法【常用技巧!】
#include <iostream>
#include <algorithm>
using namespace std;
int x;
int days[13] = {0,31,29,31,30,31,30,31,31,30,31,30,31};
bool valid(int x)
{
int year = x / 10000;
int month = x % 10000 / 100;
int day = x % 100;
if (month == 0 || month > 12) return false;
if (day == 0 || month != 2 && day > days[month]) return false;
if (month == 2)
{
bool leap = year % 100 && year % 4 ==0 || year % 400 == 0; //判断闰年
if (day > 28 + leap) return false;
}
return true;
}
bool check_ABAB(int x)
{
string s = to_string(x);
return s[0] == s[2] && s[1] == s[3] && s[0] != s[1];
}
int main()
{
int x;
cin >> x;
bool f = 1;
for(int i = 1000;i ;i ++) // 根据年份构造回文日期
{
int data = i, t = i;
for(int j = 0;j < 4;j ++ ) data = data * 10 + t % 10, t /= 10; // 生成回文日期
if(data > x && valid(data) && f){
cout << data <<endl;
f = 0;
}
if(data > x && valid(data) && check_ABAB(data)){
cout << data;
break;
}
}
return 0;
}
写法1,暴力枚举数字
#include <iostream>
#include <algorithm>
using namespace std;
int x;
int days[13] = {0,31,29,31,30,31,30,31,31,30,31,30,31};
bool valid(int x)
{
int year = x / 10000;
int month = x % 10000 / 100;
int day = x % 100;
if (month == 0 || month > 12) return false;
if (day == 0 || month != 2 && day > days[month]) return false;
if (month == 2)
{
bool leap = year % 100 && year % 4 ==0 || year % 400 == 0; //判断闰年
if (day > 28 + leap) return false;
}
return true;
}
bool check(int x)
{
int t = 0;
int xx = x;
while(x){
t = t * 10 + x % 10;
x /= 10;
}
return xx == t;
}
bool check2(int x)
{
if(!check(x)) return false;
if( x % 10 == (x / 10) % 10) return false;
string s = to_string(x);
return s[0] == s[2] && s[1] == s[3];
}
int main()
{
int x;
cin >> x;
bool f = 1,f2 = 1;
for(int i = x+ 1; ;i ++){ // 是下一个
if(valid(i)) // 合法日期
{
if(check(i) && f){
cout << i << endl;
f = 0;
}
if(check2(i) && f2){
cout << i << endl;
f2 = 0;
}
if(!f && !f2) break;
}
}
return 0;
}
写得太好了
棒棒