博客
关于我
日期类例题剖析
阅读量:817 次
发布时间:2019-03-25

本文共 1786 字,大约阅读时间需要 5 分钟。

关于日期处理的常用方法,掌握闰年的计算方式和各月的天数即可满足大部分需求。

例题剖析

回文日期

2020年蓝桥杯A组

样例输入:20200202

样例输出:2021120221211212

代码解析:#include

#include
using namespace std;

int days[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};bool isLeap(int year) {return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);}int getDay(int year, int month) {if (month == 2) return days[2] + isLeap(year);return days[month];}int main() {int n;cin >> n;string ans1, ans2;bool flag1 = false, flag2 = false;

for (int i = n / 10000 + 1; i <= 9999; i++) {    string a = to_string(i);    string b = a;    reverse(b.begin(), b.end());    int month = stoi(b.substr(0, 2));    int day = stoi(b.substr(2, 2));    if (month < 1 || month > 12) continue;    if (day < 1 || day > getDay(i, month)) continue;    string s1 = a.substr(0, 2);    string s2 = a.substr(2, 2);    if (!flag1) {        ans1 = a + b;        flag1 = true;    }    if (!flag2 && s1 == s2 && s1[0] != s1[1]) {        ans2 = a + b;        flag2 = true;    }    if (flag1 && flag2) break;}cout << ans1 << endl;cout << ans2 << endl;

}

跑步锻炼

2020年蓝桥杯B题

代码解析:#include

using namespace std;

int days[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};bool isLeap(int year) {return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);}int getDay(int year, int month) {if (month == 2) return days[2] + isLeap(year);return days[month];}

int main() {int ans = 0, weekday = 4;for (int i = 2000; i < 2020; i++) {for (int j = 1; j <= 12; j++) {for (int k = 1; k <= getDay(i, j); k++) {weekday = (weekday + 1) % 7;if (k == 1 || weekday == 0) ans += 2;else ans++;}}}for (int j = 1; j < 10; j++) {for (int k = 1; k <= getDay(2020, j); k++) {weekday = (weekday + 1) % 7;if (k == 1 || weekday == 0) ans += 2;else ans++;}}ans += 2; // 2020.10.1cout << ans << endl;}

答案: 8879

转载地址:http://mbayk.baihongyu.com/

你可能感兴趣的文章
npm的“--force“和“--legacy-peer-deps“参数
查看>>
npm的安装和更新---npm工作笔记002
查看>>
npm的常用配置项---npm工作笔记004
查看>>
npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
查看>>
npm编译报错You may need an additional loader to handle the result of these loaders
查看>>
npm设置淘宝镜像、升级等
查看>>
npm设置源地址,npm官方地址
查看>>
npm配置安装最新淘宝镜像,旧镜像会errror
查看>>
NPM酷库052:sax,按流解析XML
查看>>
npm错误 gyp错误 vs版本不对 msvs_version不兼容
查看>>
npm错误Error: Cannot find module ‘postcss-loader‘
查看>>
npm,yarn,cnpm 的区别
查看>>
NPOI之Excel——合并单元格、设置样式、输入公式
查看>>
NPOI初级教程
查看>>
NPOI利用多任务模式分批写入多个Excel
查看>>
NPOI在Excel中插入图片
查看>>
NPOI将某个程序段耗时插入Excel
查看>>
NPOI格式设置
查看>>
NPOI设置单元格格式
查看>>
Npp删除选中行的Macro录制方式
查看>>