466. Palindrome Date

Insert picture description here
Insert picture description here
Idea: Enumerate all years (equivalent to enumerating only the first four digits of eight digits), then turn it into a palindrome number, and then judge whether the palindrome number is a legal date
code

# include<iostream>
# include<cstring>
# include<cstdio>
# include<algorithm>
using namespace std;

int days[13] = {
    
    0,31,28,31,30,31,30,31,31,30,31,30,31};

bool check(int date)//判断是否合法
{
    
    
    int year = date / 10000;
    int mouth = date % 10000 / 100;
    int day = date % 100;
    if(mouth == 0 || mouth > 12) return false;
    if(day > days[mouth] && mouth != 2 || day == 0) return false;
    if(mouth == 2)
    {
    
    
        int leap = year % 100 != 0 && year % 4 == 0 || year % 400 == 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 i = 0;i < 4;i++)//使年份变成回文数字
        {
    
        
            date = date * 10 + x % 10;
            x /= 10;
        }
        if(date >= date1 && date <= date2 && check(date))//判断该回文数是否为合法年份
        {
    
    
            res++;
        }
    }
    cout << res << endl;
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_45812180/article/details/114547431