AcWing 2867. 回文日期(C++ 简单注释)
原题链接
简单
作者:
诺亚方舟.
,
2021-03-05 12:02:37
,
所有人可见
,
阅读 1967
C++ 代码
#include <iostream>
using namespace std;
int months[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
bool check_valid(int date)
{
int year = date / 10000;
int month = date % 10000 / 100;
int day = date % 100;
if (month <= 0 || month >= 13) return false;
if (day == 0 || month != 2 && day > months[month]) return false;
if (month == 2)
{
int leap = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0);
if (day > 28 + leap) return false;
}
return true;
}
bool check(int date)
{
int year = date / 10000;
int month = date % 10000 / 100;
int day = date % 100;
if (month % 10 == day / 10) return false;
if ((month % 10 == day % 10) && (month / 10 == day / 10)) return true;
return false;
}
bool st1, st2;
int ans1, ans2;
int main()
{
int date;
cin >> date;
int year = date / 10000;
while (true)
{
int new_date = year, x = year;
for (int i = 0; i < 4; i++) new_date = new_date * 10 + x % 10, x /= 10;
if (new_date == date)
{
year++;
continue;
}
if (check_valid(new_date))
{
if (!st1) st1 = true, ans1 = new_date;
if (!st2 && check(new_date)) st2 = true, ans2 = new_date;
}
year ++;
if (st1 && st2) break;
}
printf("%d\n%d", ans1, ans2);
return 0;
}
日期问题我总结了一些模板代码,可以移步
https://www.acwing.com/blog/content/5918/