一、问题描述
二、问题分析??
? ? ? ? 这题没啥好说的,跟着题目操作编程就行,对于没有相应函数的C/C++来说相对有些麻烦,那么,我的思路就是构造所有的日期进行判断。而另一边,使用有时间转换相关函数的语言能够更简单的进行代码实现。
三、代码实现
1.C/C++实现
#include <iostream>
#include <string>
using namespace std;
int days_of_month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
// 将数字转换为二进制字符串
string toBinString(int num)
{
string str = "";
while (num != 0)
{
char t[1] = { (num % 2) + '0' };
num /= 2;
str = *t + str;
}
return str;
}
// 将二进制字符串转换为整形数
int toNum(string bStr)
{
int num = 0;
for (int i = 0; i < bStr.length(); i++)
{
num *= 2;
num += bStr[i] - '0';
}
return num;
}
// 判断是否是闰年
bool judge_year(int year)
{
bool flag = false;
if (year % 4 == 0)
{
flag = (year % 100 == 0 && year % 400 != 0) ? false : true;
}
return flag;
}
void get_dates(int * dates)
{
for (int year = 1964; year <= 2020; year++)
{
bool flag = judge_year(year);
for (int month = 1; month <= 12; month++)
{
int max_day = days_of_month[month - 1];
// 闰年 2 月 29 天
max_day = (month == 2 && flag) ? (max_day + 1) : max_day;
for (int day = 1; day <= max_day; day++)
{
int num = year * 10000 + month * 100 + day;
string temp = toBinString(num);
reverse(temp.begin(), temp.end());
if (num == toNum(temp))
{
// 就算数组不够大,这里的赋值也不会报错
*(dates++) = num;
}
}
}
}
}
int main()
{
int dates[20] = { 0 };
get_dates(dates);
if (dates[19] == 0) // 最后一个是0说明没有溢出
{
for (int i = 0; i < 20 && dates[i] != 0; i++)
{
cout << dates[i] << endl;
}
}
else
{ // 溢出提示
cout << "error!" << endl;
}
return 0;
}
2.Python实现
# coding=utf-8
import datetime
def get_dates():
date = datetime.datetime.strptime('19641010', '%Y%m%d')
end_date = datetime.datetime.strptime('20200724', '%Y%m%d')
while date < end_date:
num = int(date.strftime('%Y%m%d'))
r_num = int(bin(num)[2:][::-1], 2)
if num == r_num:
yield num
date += datetime.timedelta(days=1)
if __name__ == '__main__':
dates = [i for i in get_dates()]
print(dates)
pass
|