AcWing_466 回文日期(枚举、日期处理)

AcWing

466. 回文日期

由于只有八位数,而且回文串左右对称,因此可以只枚举左半边,这样只需枚举1000∼9999,然后判断:

  • 是否在范围内
  • 整个八位数构成的日期是否合法

对于满足条件的日期,结果res++.

判断闰年的条件:

  • 普通闰年:公历年份是4的倍数,且不是100的倍数
  • 世纪闰年:公历年份是400的倍数
#include <bits/stdc++.h>
using namespace std;
int a, b;
int days[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
bool judgeleap(int year){
    if((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) return true;
    return false;
}
bool check(int date){
    int year = date / 10000;
    int month = date / 100 % 100;
    int day = date % 100;
    if(month >= 13 || month == 0 || day == 0) return false;
    if(month != 2 && day >= days[month] + 1) return false;
    if(judgeleap(year) && month == 2 && day >= 30) return false;
    if(!judgeleap(year) && month == 2 && day >= 29) return false;
    return true;
}
int main(){
    cin >> a >> b;
    int res = 0;
    for(int i = 1000; i <= 9999; i++){
        int n = i, r = i;
        for(int j = 1; j <= 4; j++) n = n * 10 + r % 10, r /= 10;
        if(n < a || n > b) continue;
        if(check(n)) res++;
    }
    cout << res;
    return 0;
}