466. 回文日期

https://www.acwing.com/problem/content/468/

模拟题,洛谷也有一道

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>

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 || month >= 13 || !day) return false;
	
	if (month != 2 && day > months[month]) return false;//天数大于当月最大天数
	if (month == 2)//考虑2月
	{
		bool leap = year % 4 == 0 && year % 100 || year % 400 == 0;//判断闰年,1 or 0
		if (day > 28 + leap) return false;//闰年就看看2月份天数大不大于29,平年就看大不大于28	
	}
	return true;
}

int main()
{
	int date1, date2;
	cin >> date1 >> date2;
	int res = 0;
	for (int i = 0; i < 10000; i ++ )
	{
		int x = i, r = i;
		//构造回文,对原数不断地%10,将此值放后(加上构造数),再将构造数乘10
		for (int j = 0; j < 4; j ++ ) r = r * 10 + x % 10, x /= 10;
		if (r >= date1 && r <= date2 && check(r)) res ++ ;
	}
	printf("%d\n", res);
	return 0;
}

 

posted @ 2022-10-05 14:59  风乐  阅读(17)  评论(0)    收藏  举报