计算年份在1000≤year≤3000间,年月日构成回文数的个数
例:20211202为回文数
首先判断年份逆序中月份,日期是否合法;然后判断月份的天数,二月的天数依据是否为闰年判断;最后将月份日期与年份结合组合为回文数。
#include <stdio.h>
int main() {
int year, day, y, ymd;
int month;
int h; /*用于标识判断结果:为0时不构成回文日期,不为0时,构成回文日期*/
int count = 0;/*计算回文日期个数*/
for (year = 1000; year < 3000; year++) {/*年份在1000≤year≤3000*/
y = year; /*把年份赋值给y,y储存后四位数,判断是否年份倒数是否为合法日期*/
month = y % 100; /*原年份的后两位对应月份*/
month = (month % 10) * 10 + month / 10; /*月份输出*/
day = y / 100; /*原年份的前两位对应日*/
day = (day % 10) * 10 + day / 10; /*日期输出*/
h = 0;
switch (month) { /*十二月份天数,判断日期合法*/
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if (day <= 31)
h = 1;
break;
case 4:
case 6:
case 9:
case 11:
if (day <= 30)
h = 1;
break;
case 2:/*二月份判断天数*/
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) { /*判断是否为闰年*/
if (day <= 29)
h = 1;
} else {
if (day <= 28)
h = 1;
}
break;
default:
continue; /*后两位倒过来构不成月份,则结束本次循环,然后进行下一次是否执行循环的判定*/
}
if (h != 0) { /*能构成回文日*/
y = year;/*年份赋值给y,形成年月日格式输出*/
ymd = year; /*年份赋值给年月日,构造出年月日的形式供输出*/
while (y > 0) {/*形成年月日格式输出*/
ymd = ymd * 10 + y % 10;
y = y / 10;
}
printf("%d\t", ymd);
count++;
if (count % 5 == 0)
printf("\n");
}
}
printf("\n");
printf("共有 %d 个回文日期\n", count);
return 0;
}