#1185. 一周中的第几天
查了百度,得知1970.1.1是周四,然后在这个基础上得到所求日期比1970.1.1多出来的日子,再%7就可以知道是星期几啦。因为7%7=0,所以0就代表周日。
char * dayOfTheWeek(int day, int month, int year){
int A[13]={0,31,59,90,120,151,181,212,243,273,304,334,365};
int B[13]={0,31,60,91,121,152,182,213,244,274,305,335,366};
int num=4;
for(int i=1971;i<=year;++i){
if((i-1)%4==0&&(i-1)%100||(i-1)%400==0){
num+=366;
}
else num+=365;
}
if(year%4==0&&year%100||year%400==0){
num+=B[month-1]+day-1;
}
else num+=A[month-1]+day-1;
num%=7;
if(num==0) return "Sunday";
else if(num==1) return "Monday";
else if(num==2) return "Tuesday";
else if(num==3) return "Wednesday";
else if(num==4) return "Thursday";
else if(num==5) return "Friday";
else return "Saturday";
}
之前以为C语言只能用char a[],想着一个一个字符也太麻烦了。后来经Amy大佬提醒原来可以char a[][],来二维定义各个字符串。不过返回字符串要给它分配空间。
参考的兴磊大佬的题解
https://bbs.csdn.net/topics/602906969
char * dayOfTheWeek(int day, int month, int year){
int A[13]={0,31,59,90,120,151,181,212,243,273,304,334,365};
int B[13]={0,31,60,91,121,152,182,213,244,274,305,335,366};
char s[7][10]={"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};//二维保存字符串
char *ans=malloc(sizeof(char)*10);
int num=4;
for(int i=1971;i<=year;++i){
if((i-1)%4==0&&(i-1)%100||(i-1)%400==0){
num+=366;
}
else num+=365;
}
if(year%4==0&&year%100||year%400==0){
num+=B[month-1]+day-1;
}
else num+=A[month-1]+day-1;
num%=7;
strcpy(ans,s[num]);//这个是一个字符串复制函数,将后一个复制到前一个里
return ans;
}
#1154. 一年中的第几天
从字符串中得到日期的数值,这段代码参考了英雄哥的文章,代码中的date+5,date+8是改变了这个指针的初始地址,分别从原来的date[0]到date[5]和date[8]。
int A[13]={0,31,59,90,120,151,181,212,243,273,304,334,365};
int B[13]={0,31,60,91,121,152,182,213,244,274,305,335,366};
int nyr(char* s,int length){
int sum=0;
for(int i=0;i<length;++i){
sum=sum*10+s[i]-'0';
}
return sum;
}
int dayOfYear(char * date){
int year=nyr(date,4);
int month=nyr(date+5,2);
int day=nyr(date+8,2);
int num=0;
if(year%4==0&&year%100||year%400==0){
num+=B[month-1]+day;
}
else num+=A[month-1]+day;
return num;
}
#1360. 日期之间隔几天
这个题实际上是前两个题的一个综合,我写的起来挺臭长的,有待改进。或许可以再定义一个函数求到1970.1.1的时间,就像第一题一样。然后两个数一减就行。
int A[13]={0,31,59,90,120,151,181,212,243,273,304,334,365};
int B[13]={0,31,60,91,121,152,182,213,244,274,305,335,366};
int nyr(char* s,int length){
int sum=0;
for(int i=0;i<length;++i){
sum=sum*10+s[i]-'0';
}
return sum;
}
int daysBetweenDates(char * date1, char * date2){
int year1=nyr(date1,4);
int month1=nyr(date1+5,2);
int day1=nyr(date1+8,2);
int year2=nyr(date2,4);
int month2=nyr(date2+5,2);
int day2=nyr(date2+8,2);
int num=0;
int num1=0,num2=0;
if(year1>year2){
int a=year1;
year1=year2;
year2=a;
a=month1;
month1=month2;
month2=a;
a=day1;
day1=day2;
day2=a;
}
for(int i=year1+1;i<=year2;++i){
if((i-1)%4==0&&(i-1)%100||(i-1)%400==0){
num+=366;
}
else num+=365;
}
if(year1%4==0&&year1%100||year1%400==0){
num1+=B[month1-1]+day1-1;
}
else num1+=A[month1-1]+day1-1;
if(year2%4==0&&year2%100||year2%400==0){
num2+=B[month2-1]+day2-1;
}
else num2+=A[month2-1]+day2-1;
num+=num2-num1;
return num>=0? num:-num;
}