题目
给出年分m和一年中的第n天,算出第n天是几月几号。
输入描述: 输入包括两个整数y(1<=y<=3000),n(1<=n<=366)。
输出描述: 可能有多组测试数据,对于每组数据, 按 yyyy-mm-dd的格式将输入中对应的日期打印出来
示例1
输入
2000 3
2000 31
2000 40
2000 60
2000 61
2001 60
输出
2000-01-03
2000-01-31
2000-02-09
2000-02-29
2000-03-01
2001-03-01
思路
套模板(×
代码
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define ISYEAP(x) (x%100!=0 && x%4==0) || (x%400==0) ? 1 : 0
int dayOfMonth[13][2] = {
0,0,
31,31,
28,29,
31,31,
30,30,
31,31,
30,30,
31,31,
31,31,
30,30,
31,31,
30,30,
31,31
};
char outputName[13][3] = {
"","01","02","03","04","05","06","07","08","09","10","11","12"
};
struct Date{
int year;
int month;
int day;
void nextDay(){
day ++;
if(day > dayOfMonth[month][ISYEAP(year)]){
day=1;
month++;
if(month>12){
month=1;
year++;
}
}
}
};
int buf[3001][13][32]; //1-3000,1-12,1-31
int main(){
Date tmp;
tmp.year=1;
tmp.month=1;
tmp.day=1;
int cnt=0;
while(tmp.year!=3001){
buf[tmp.year][tmp.month][tmp.day]=cnt;
tmp.nextDay();
cnt++;
}
int y,days;
while(scanf("%d%d",&y,&days)!=EOF){
int first = buf[y][1][1];
for(int m=1;m<=12;m++){
for(int d=1; d<= dayOfMonth[m][ISYEAP(y)];d++){
int target = buf[y][m][d];
if(target-first+1 == days){
cout << y << "-" << outputName[m] << "-";
if(d<10){
cout << outputName[d] << endl;
}
else cout << d << endl;
}
}
}
}
}
参考代码
链接:https://www.nowcoder.com/questionTerminal/b1f7a77416194fd3abd63737cdfcf82b
来源:牛客网 @Riroaki
/*其实只要建立两个数组分别存放闰年和非闰年的各个月份对应天数就可以了*/
#include<stdio.h>
int a[13]={0,31,28,31,30,31,30,31,31,30,31,30,31},
b[13]={0,31,29,31,30,31,30,31,31,30,31,30,31};
int main(void){
int year,day,month;
while(scanf("%d%d",&year,&day)!=EOF){
month=0;
if(year%4==0&&year%100!=0||year%400==0)
{while(day>b[month])day-=b[month],month++;
printf("%04d-%02d-%02d\n",year,month,day);
}
else
{while(day>a[month])day-=a[month],month++;
printf("%04d-%02d-%02d\n",year,month,day);
}
}return 0;
}