日期问题

模拟日期

1. 回文日期

  • 从这道题中主要学习的思路是:直接用int型数据模拟日期,从而进行枚举,再判断这个日期是否合法,是否满足题目的要求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include<bits/stdc++.h>
#define x first
#define y second

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;

// 题目描述: 日期问题,跟shit一样,但是做一遍找到规律就没问题了
// 输入一个起始日期和一个终止日期,最后返回这个日期中有多少个日期是回文的
// 换个思路,我们枚举所有的回文数,因为前四位确定了后四位就一定确定了
// 前四位>=1000,又因为是四位数,所以最大9999,范围则[1000,9999]
// 把字符串拼接起来过后再去判断日期是否合法
// 如何判断一个日期是否在两个日期之间?字典序嘛,不用想复杂了
// 最后如何判断日期是否合法呢?用一个数组month存储每一个月的状态
// 对于2月,还要考虑平年和闰年的情况

int months[13]={0,31,28,31,30,31,30,31,31,30,31,30,31}; // 1~12月的天数,平年

// 判断日期是否合法,完全可以当模板
bool check(int date) {
int year=date/10000; // 取前四位
int month=date%10000/100; // 后四位的前两位
int day=date%100;

// 如果月份不合法和天数=0
if(!month || month>=13 || !day) return false;
// 平年下天数不合法
if(month!=2 && day>months[month]) return false;
// 月份为2,单独判断是否为闰年以及合法与否
if(month==2) {
// 四年一闰,百年不闰,四百年又闰
bool leap= year%4==0 && year%100 || year%400==0;
if(day>months[month]+leap) {
return false;
}
}
return true;
}

int main() {
int date1,date2;
cin>>date1>>date2; // 开始和结束日期
int res=0;
// 只枚举年份
for(int i=1000;i<10000;i++) {
int date=i,x=i;
// 拼接成回文数
for(int j=0;j<4;j++) {
date=date*10+x%10; // 取后四位的最后一位拼上来
x/=10;
}
if(date1<=date && date<=date2 && check(date)) res++;
}
cout<<res;
return 0;
}

2. 顺子日期

  • 本题要学的思路是用sprintf函数将指定格式的int型的year, month, day的值输入到字符数组中制造字符串
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include<bits/stdc++.h>
#define x first
#define y second

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;

// 题目描述: YYYYMMdd这个日期格式中若出现三个升序连续的数字,记为顺子年

const int N=1e5+5;

// 题目只要求找2022年,这是一个平年
const int months[]={
0,31,28,31,30,31,
30,31,31,30,31,30,
31
};

// 字符串表示日期,判断是否为顺子年
bool check(string str) {
for(int i=0;i+2<str.length();i++) {
if(str[i+1]==str[i]+1 && str[i+2]==str[i+1]+1 && str[i]!='0') {
return true;
}
}
return false;
}

int main() {
int year=2022,month=1,day=1;
int res=0;
// 一年中
for(int i=0;i<365;i++) {
char str[10];
// 用sprintf函数按照指定格式制造字符串
sprintf(str,"%04d%02d%02d",year,month,day); // %04d不足4位自动补0
if(check(str)) {
res++;
cout<<str<<endl;
}
// 进月
if(++day>months[month]) {
day=1;
month++;
}
}
cout<<res<<endl;
return 0;
}
打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2015-2024 John Doe
  • 访问人数: | 浏览次数:

请我喝杯咖啡吧~

支付宝
微信