日期类问题
求两天之间的时间差
统一的思想:将两个日期之差转换为这两个日期与0000年1月1日的日期差的差值。
好处是预处理,能够把所有的日期差存起来,这就是空间换时间的思想。
然后还有一个需要注意的是闰年的处理。在不被100整除的情况下被4整除,或者被四百整除
#define isYeap(x) x%100!=0 && x&40 || x%4000 ?1:0
存储一个数组,存储闰年/非闰年 每个月有多少天
定义一个结构,存储天,月,年,还有一个函数,计算下一天的年月日
#include<iostream>
using namespace std;
//输入两个日期,求这两个天数之差
//首先是判断是否闰年
//判断闰年的方法:不被100整除被4整除或者被四百整除
#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 main()
{
Date tmp;
int cnt = 0;
tmp.Day = 1;
tmp.Year = 0;
tmp.Month = 1;
while (tmp.Year!=5001)
{
buf[tmp.Year][tmp.Month][tmp.Day] = cnt;
cnt++;
tmp.nextDay();
}
int d1, m1, y1;
int d2, m2, y2;
while (scanf_s("%4d%2d%2d",&y1,&m1,&d1)!=EOF)
{
scanf_s("%4d%2d%2d", &y2, &m2, &d2);
printf("%d\n", abs(buf[y1][m1][d1] - buf[y2][m2][d2]+1));
}
return 0;
}
两点注意的:
(1)计算特定日期与原点日期的天数之差,使用了三维数组存储,下标分别是年月日,这其实是hash的思想
(2)相对耗内存的数组定义为全局变量会比较好
计算今天是星期几
前面都一样
#include<string>
using namespace std;
//输入两个日期,求这两个天数之差
//首先是判断是否闰年
//判断闰年的方法:不被100整除被4整除或者被四百整除
#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];
//给定特定的日期,计算是星期几
string monthname[12] = {
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"Sepetember",
"October",
"November",
"December"
};
char weekname[7][20] = {
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
};
void dayofweek()
{
Date tmp;
int cnt = 0;
tmp.Day = 1;
tmp.Year = 0;
tmp.Month = 1;
while (tmp.Year != 5001)
{
buf[tmp.Year][tmp.Month][tmp.Day] = cnt;
cnt++;
tmp.nextDay();
}
int d1, m1, y1;
int d2, m2, y2;
y1 = 2020;
m1 = 5;
d1 = 14;
//char s[20];
string s;
//int days=abs(b)
//输入字符串还是cin比较方便
while (cin>>d2>>s>>y2)
{
//scanf_s("%s", &s,7);
//scanf_s("%d", &y2);
int i = 0;
for ( i = 0; i < 12; i++)
{
if (monthname[i]==s)
{
break;
}
}
int days = buf[y2][i + 1][d2] - buf[y1][m1][d1]+3;
puts(weekname[(days % 7 + 7) % 7]);
}
}
1万+

被折叠的 条评论
为什么被折叠?



