人们习惯用8位数字表示一个日期,其中,前4位代表年份,接下来2位代表月份,最后2位代表日期。一个日期是回文的,当且仅当表示这个日期的8位数字是回文的。
现在,我们想知道在指定的两个日期之间(包含这两个日期本身),有多少个日期是回文的?
一个8位数字是回文的,当且仅当对于所有的i(1≤i≤ 8)从左向右数的第i个数字和从右向左数的第i个数字是相同的。例如:
·对于2016年11月19日,用8位数字20161119表示,它不是回文的。
·对于2010年1月2日,用8位数字20100102表示,它是回文的。
·对于2010年10月2日,用8位数字20101002表示,它不是回文的。
实现代码如下:
#pragma warning(disable:4996)
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
//定义一个能将四位数倒序表示的函数
int re(num) {
int a, b, c, d, e;
a = num / 1000;
b = (num - a * 1000) / 100;
c = (num - a * 1000 - b * 100) / 10;
d = (num - a * 1000 - b * 100 - c * 10);
e = d * 1000 + c * 100 + b * 10 + a;
return e;
}
int main()
{
int start, end;
printf("请输入一个八位数以表示日期(例如:20211230):");
scanf("%d",&start);
printf("请输入一个晚于上面的日期:");
scanf("%d",&end);
int year1 = start / 10000;
int year2 = end / 10000;
int d1 = start - year1 * 10000;
int d2 = end - year2 * 10000;
int date1 = re(year1);
int date2 = re(year2);
int count = 0;
//判断开始和结束年份里有没有可能有回文数
if (d1 > date1) {
year1 += 1;
}
if (d2 < date2) {
year2 -= 1;
}
//判断中间年份里有没有回文数
for (int year = year1; year <= year2; year++) {
int date = re(year);
int mouth = date / 100;
int day = date - mouth * 100;
//判断表示的日期是否正常
if ((year % 100 != 0 && year % 4 == 0) || year % 400 == 0) {
switch (mouth) {
case 2:
if (day <= 29) {
count += 1;
}
break;
case 4:
case 6:
case 9:
case 11:
if (day <= 30) {
count += 1;
}
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if (day <= 31) {
count += 1;
}
break;
}
}
else {
switch (mouth) {
case 2:
if (day <= 28) {
count += 1;
}
break;
case 4:
case 6:
case 9:
case 11:
if (day <= 30) {
count += 1;
}
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if (day <= 31) {
count += 1;
}
break;
}
}
}
printf("有%d个回文数年", count);
}