枚举年份,构造检验
#include <iostream>
using namespace std;
int tmp[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int st, ed;
bool check(int t){
int a[4];
int year = t, i = 0;
bool leap = year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
while(t){
a[i ++ ] = t % 10;
t /= 10;
}
int month = a[0] * 10 + a[1];
int day = a[2] * 10 + a[3];
int all = year * 10000 + month * 100 + day;
if(all > ed || all < st) return false;
if(month != 2){
if(month > 0 && month <= 12 && day && day <= tmp[month]) return true;
else return false;
}else{
if(tmp[month] + leap >= day) return true;
else return false;
}
}
int main(){
cin >> st >> ed;
int startYear, endYear;
startYear = st / 10000;
endYear = ed / 10000;
int cnt = 0;
for(int i = startYear; i <= endYear; i ++ ){
if(check(i)) cnt ++ ;
}
cout << cnt << endl;
return 0;
}
纯模拟日历
#include <iostream>
using namespace std;
int tmp[13] = {0, 31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31};
int startYear, startMonth, startDay;
int endYear, endMonth, endDay;
int nYear, nMonth, nDay;
void nextDay(int year, int month, int day){
int flag = (year % 4 == 0 && year % 100 != 0 || year % 400 == 0);
if(flag){
tmp[2] = 29;
}else{
tmp[2] = 28;
}
nDay = day + 1;
nMonth = month;
nYear = year;
if(nDay > tmp[month]){
nMonth ++ ;
nDay = 1;
}
if(nMonth > 12){
nYear ++ ;
nMonth = 1;
}
}
bool isFit(int year, int month, int day){
char s[8];
s[3] = year % 10 + '0';
s[2] = year % 100 / 10 + '0';
s[1] = year % 1000 / 100 + '0';
s[0] = year / 1000 + '0';
s[4] = month / 10 + '0';
s[5] = month % 10 + '0';
s[6] = day / 10 + '0';
s[7] = day % 10 + '0';
bool res = true;
for(int i = 0; i < 4; i ++ ){
if(s[i] != s[7 - i]){
res = false;
break;
}
}
return res;
}
int main(){
string s;
string e;
cin >> s;
cin >> e;
startDay = (s[6] - '0') * 10 + (s[7] - '0');
startMonth = (s[5] - '0') + (s[4] - '0') * 10;
startYear = (s[3] - '0') + (s[2] - '0') * 10 + (s[1] - '0') * 100 + (s[0] - '0') * 1000;
endDay = (e[6] - '0') * 10 + (e[7] - '0');
endMonth = (e[5] - '0') + (e[4] - '0') * 10;
endYear = (e[3] - '0') + (e[2] - '0') * 10 + (e[1] - '0') * 100 + (e[0] - '0') * 1000;
int res = 0;
nYear = startYear;
nMonth = startMonth;
nDay = startDay;
while(true){
if(nYear == endYear && nMonth == endMonth && nDay == endDay){
break;
}
if(isFit(nYear, nMonth, nDay)){
res ++ ;
}
nextDay(nYear, nMonth, nDay);
}
if(isFit(nYear, nMonth, nDay)){
res ++ ;
}
cout << res << endl;
return 0;
}