世界完全对称日计算(C++)

今天是世界完全对称日(2011 1102),所以就想写一个算法来计算一段时间内所有的完全对称日。看看有多少日期是世界完全对称日

描述:
输入开始和结束年份,求出其中所有的完全对称日。

输入:

输入开始年份startYear和结束年份endYear (startYear < endYear);

输出:

输出所要求的完全对称日。

解题思路:

1)根据月份和天,逆序后算出对应的年份的日期 (如1月1号 -> 0101 -> 1010,则年份是1010年)

2)判断计算出来的年份是否在输入的年份之间

3)排除非闰年时2月29号这个不合法日期

代码:

#include <vector>
#include <string>
#include <sstream>
#include <iomanip>
#include <algorithm>
using namespace std;

const int MonthDays[] ={
31,29,31,30,31,30,31,31,30,31,30,31
};

class SymmetricalDay
{
public:

bool isLeap(int year)
{
return (( year % 4 == 0 ) && ( year % 100 != 0 ) || ( year % 400 == 0 ));
}

vector<string> getDays(int startYear, int endYear)
{
vector<string> results;

for (int curMonth = 1; curMonth <= 12; ++curMonth)
{
for (int curDay = 1; curDay <= MonthDays[curMonth-1]; ++curDay)
{
ostringstream tempValue;

tempValue << setw(2) << setfill('0') << curMonth;
tempValue << setw(2) << setfill('0') << curDay;

string strData(tempValue.str());
string strReverse(strData.rbegin(), strData.rend());

istringstream yearValue(strReverse);

int curYear = 0;
yearValue >> curYear;

if (curYear >= startYear && curYear <= endYear)
{
if (!isLeap(curYear) && curMonth==2 && curDay==29)
{
continue;
}

string tempResult = yearValue.str() + "" + tempValue.str();
results.push_back(tempResult);
}
}
}

sort(results.begin(), results.end());

return results;
}
};



原文地址:https://www.cnblogs.com/Quincy/p/2233493.html