codeup 1928 日期处理 两种解法

第一种是《算法笔记》中的解法。
第二种解法的速度比第一种快点,但写法相对复杂点。
两种解法都AC了。

//第一种解法 
#include <cstdio>
int month[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}};
bool isLeap(int year)
{
	return (year%4==0)&&(year%100!=0)||(year%400==0);
}
int main()
{
	int time1, time2;
	int y1,m1,d1;
	int y2,m2,d2;
	while(scanf("%d%d",&time1,&time2)!=EOF)
	{
		if(time1>time2)
		{
			int temp=time1;
			time1=time2;
			time2=temp;
		}
		y1=time1/10000,m1=time1%10000/100,d1=time1%100;
		y2=time2/10000,m2=time2%10000/100,d2=time2%100;

		int ans=1;
		while(y1!=y2||m1!=m2||d1!=d2)
		{
			d1++;
			if(d1>month[m1][isLeap(y1)]){
				m1++;
				d1=1; 
			}
			if(m1==13){
				y1++; 
				m1=1;
			} 
			ans++;	

		}
		printf("%d\n",ans);
	}
	return 0;
}
//第二种解法 
#include <cstdio>
int month[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}};
bool isLeap(int year)
{
	return (year%4==0&&year%100!=0)||(year%400==0);
}
int main()
{
	int time1, time2;
	int y1,m1,d1;
	int y2,m2,d2;
	while(scanf("%d%d",&time1,&time2)!=EOF)
	{
		if(time1>time2)
		{
			int temp=time1;
			time1=time2;
			time2=temp;
		}
		y1=time1/10000,m1=time1%10000/100,d1=time1%100;
		y2=time2/10000,m2=time2%10000/100,d2=time2%100;

		int ans;
		int temp1=0, temp2=1;
		int m22=1, d22=1;
		int addyears=0; 
		
		if((y2-y1)>=2){
			for(int i=y1+1;i<y2;i++){
				if(isLeap(i))
					addyears+=366;
				else
					addyears+=365;
			}
			while(m1!=13){
				d1++;
				if(d1==month[m1][isLeap(y1)]+1){
					m1++;
					d1=1;
				}
				temp1++;
			}
			while(m22<m2||d22<d2){
				d22++;
				if(d22==month[m22][isLeap(y2)]+1){
					m22++;
					d22=1;
				}
				temp2++;
			}
			ans=addyears+temp1+temp2;
		}
		else if(y2==y1+1){
			while(m1!=13){
				d1++;
				if(d1==month[m1][isLeap(y1)]+1){
					m1++;
					d1=1;
				}
				temp1++;
			}
			while(m22<m2||d22<d2){
				d22++;
				if(d22==month[m22][isLeap(y2)]+1){
					m22++;
					d22=1;
				}
				temp2++;
			}
			ans=temp1+temp2;
		}
		else{
			while(m1<m2||d1<d2){
				d1++;
				if(d1==month[m1][isLeap(y1)]+1){
					m1++;
					d1=1;
				}
				temp2++;
				
			}
			ans=temp2;
		}
		printf("%d\n",ans);
	}
	return 0;
}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 1024 设计师:白松林 返回首页