$\it{***方法一(日期问题模板)***}$
思路:从当前年1.1号开始加,剩余天数逐减直到为0,日期即为所求;用一个数组记录平年每个月的天数
,日期号变量d每次自增
,并判断是否超出当前记录月份天数,超出则月份变量m自增
,并判断是否超出月份数,超出则年份自增
要点:
1.日期问题模板
:一个数组记录平年每月天数
;一个函数判断是否为闰年
;一个函数求某年某月的天数
2.判断语句的条件判断代码一定会执行
(所以日期d每次都会自增),语句体只有当条件满足才执行
3.printf格式化输出
4.判断是否为闰年
:世纪年可以整除400
;非世纪年可以整除4不能整除100
代码:
#include<bits/stdc++.h>
using namespace std;
//记录平年每个月天数的数组
const int months[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
//判断闰年函数
int is_leap(int year)
{
//能被4整除但不能被100整除(非世纪年)
//能被400整除(世纪年)
if(year%4==0&&year%100||year%400==0) return 1;
return 0;
}
//获取某年某月天数的函数
int get_days(int y,int m)
{
if(m==2) return months[m]+is_leap(y);
return months[m];
}
int main()
{
int y,s;
while(cin>>y>>s)
{
int m=1,d=0;
while(s--)
{
if(++d>get_days(y,m))
{
d=1;
if(++m>12)
{
m=1;
y++;
}
}
}
printf("%04d-%02d-%02d\n",y,m,d);
}
return 0;
}
$\it{***方法二(暴力)***}$
思路:逐月减天数,与上略同,暴力实现
代码:
#include<bits/stdc++.h>
using namespace std;
//判断闰年函数
bool isLeapYear(int year)
{
//能被4整除但不能被100整除(非世纪年)
if((year%4==0)&&(year%100)) return 1;
//能被400整除(世纪年)
if(year%400==0) return 1;
return 0;
}
int main()
{
string str;
while(getline(cin,str,'\n'))
{
stringstream ssin(str);
int y,d;
ssin>>y>>d;
int month=1;
//判断是否为闰年
bool q=isLeapYear(y);
while(!(((month==2)&&!q&&(d<=28))||((month==2)&&q&&(d<=29))||((month==1||month==3||month==5||month==7||month==8||month==10||month==12)&&(d<=31))||((month==4||month==6||month==9||month==11)&&(d<=30))))
{
//判断是否满足进位条件
bool p;
if(month==1||month==3||month==5||month==7||month==8||month==10||month==12)
{
p=d>31;
d=p?d-31:d;
if(p) month++;
}
else if(month==2)
{
if(q)
{
p=d>29;
d=d>29?d-29:d;
if(p) month++;
}
else
{
p=d>28;
d=d>28?d-28:d;
if(p) month++;
}
}
else if(month==4||month==6||month==9||month==11)
{
p=d>30;
d=p?d-30:d;
if(p) month++;
}
}
string res;
if(y>=1000) res+=to_string(y);
else if(y>=100) res=res+'0'+to_string(y);
else if(y>=10) res=res+"00"+to_string(y);
else res=res+"000"+to_string(y);
res+='-';
if(month<10) res+=to_string(0);
res+=to_string(month);
res+='-';
if(d<10) res+=to_string(0);
res+=to_string(d);
cout<<res<<endl;
}
return 0;
}