机试:日期类问题

#include<stdio.h>
#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
};
//定义了一个类,不仅可以用来表示日期,还能够自动计算出下一个日期 
struct Date{
	int day;
	int month;
	int year;
	void nextday(){
		day++;
		if(day>dayofmonth[month][isyeap(year)]){
			day=1;
			month++;
			if(month>12){
				month=1;
				year++;
			}
		}
	}
};

int buf[5001][13][32];
//返回绝对值 
int abs(int x){
	return x<0?-x:x;
}

int main(){
	Date tmp;
	int cnt=0;
	tmp.day=1;
	tmp.month=1;
	tmp.year=0;
	//预处理数据
	//先计算并保存每年每月每日与0年1月1日的日期差 
	while(tmp.year!=5001){
		buf[tmp.year][tmp.month][tmp.day]=cnt;
		tmp.nextday();
		cnt++;
	}
	int d1,m1,y1;
	int d2,m2,y2;
	while(scanf("%4d%2d%2d",&y1,&m1,&d1)!=EOF){
		//使用%4d来读取该八位数输入的前四位并赋值给代表年的变量 
		scanf("%4d%2d%2d",&y2,&m2,&d2);
		printf("%d\n",abs(buf[y2][m2][d2]-buf[y1][m1][d1])+1);
		//hash的思想:用年、月 、日分别表示该数组下标
		 
	}
	return 0;
}

这个解法真的很棒呀,简直是一气呵成~

那么当这个问题升级到英文版本,又回怎样呢?

题目大意为:输入一个日期 要求输入该天是星期几

那么我们只需要知道 1.今天是星期几 2.今天和所给的那天相隔几天

#include<stdio.h>
#include<string.h>
#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
};
struct Date{
	int day;
	int month;
	int year;
	void nextday(){
		day++;
		if(day>dayofmonth[month][isyeap(year)]){
			day=1;
			month++;
			if(month>12){
				month=1;
				year++;
			}
		}
	}
};
int buf[3001][13][32];
char monthname[13][20]={
"",
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
};

char weeknAame[7][20]={
"Sunday",
"Monday",
"Tuesady",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
};
int main()
{
	Date tmp;
	int cnt=0;
	tmp.day=1;
	tmp.month=1;
	tmp.year=0;
	while(tmp.year!=3001){
		buf[tmp.year][tmp.month][tmp.day]=cnt;
		tmp.nextday();
		cnt++;
	} 
	int d,m,y;
	char s[20];
	while(scanf("%d%s%d",&d,&s,&y)!=EOF){
		for(m=1;m<=12;m++){
			if(strcmp(s,monthname[m])==0){
				break;
			}
		}
		int days=buf[y][m][d]-buf[2019][4][10];
		days+=3;//+3因为2019.4.10是星期三 
		puts(weekname[(days%7+7)%7]);
		//若为负数 则还要保证该下标为正 简单地处理成余数加7再求模 
	}return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值