AcWing 466. 回文日期
原题链接
简单
作者:
隐灵
,
2024-03-13 20:45:01
,
所有人可见
,
阅读 9
详解 带注释
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
//列举12个月的天数,一月用days[1]表示,以此类推
int days[13] = {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 > 12) return false;
if (day == 0 || month != 2 && day > days[month]) return false; //先判断不是二月的情况
//判断平年还是润年
if (month == 2)
{
int leap = year % 100 && year % 4 == 0 || year % 400 == 0; //是闰年返回值就是1,不是闰年返回值是0
if (day > 28 + leap) return false; //如果天数大于二月的天数,则错误
}
return true;
}
int main()
{
int date1, date2;
cin >> date1 >> date2; //输入起始日期和终止日期
//先列举回文数,再判断回文数是否满足要求
int res = 0; //判断满足日期要求的回文数的数量
for (int i = 1000; i < 10000; i ++ ) //先输入年份
{
int date = i, x = i;
for (int j = 0; j < 4; j ++ ) //将后四位反转拼接在data后面
{
date = date * 10 + x % 10; //*10将个位变成0,再取x的个位,加上去
x /= 10; //将x的个位删除
}
if (date1 <= date && date <= date2 && check_valid(date)) res ++ ; //check检查日期是否合法
}
cout << res << endl;
return 0;
}
//四润百不润,四百一润