C++ 蓝桥杯:特殊时间

禁止转载,该文章内容并非教学,仅为个人笔记 。
问题描述
2022 年 2 月 22 日 22:20 是一个很有意义的时间,
年份为 2022,由 3 个 2 和 1 个 0 组成,
如果将月和日写成 4 位,为 0222,也是由 3 个 2 和 1 个 0 组成,
如果将时间中的时和分写成 4 位,还是由 3 个 2 和 1 个 0 组成 。
小蓝对这样的时间很感兴趣,他还找到了其它类似的例子,比如 111 年 10 月 11 日 01:11,2202 年 2 月 22 日 22:02 等等 。
【C++蓝桥杯:特殊时间】请问,总共有多少个时间是这种年份写成 4 位、月日写成 4 位、时间写成4 位后由 3 个一种数字和 1 个另一种数字组成 。注意 1111 年 11 月 11 日11:11不算,因为它里面没有两种数字 。

C++  蓝桥杯:特殊时间

文章插图
解题思路
数据中要特别注意的是日月组合,因为一个月有几天取决于月份 。
看下图,在可能的最大组合值中,有且仅有日月组合为 11 月 31 日 是无效的,排除日月组合中所有日大于等于31即可 。
2月的最大组合是 02 月 22 日,所以不用考虑闰年问题 。
代码实现
#includeusing namespace std;void IsOk(int&, int&, int&);int Numbers[4], Count;int main(){for (int j = 0; j < 10; ++j){for (int k = 0; k < 10; ++k) // j,k 为种子数据,接下来生成的年月日时分都由种子数据组成{if(j == k) continue;int y = 0, m = 0, hs = 0;// y,m,hs 为由当前种子组成下可以分别满足条件的年,月日,时分总数for (int i = 0; i < 4; ++i){Numbers[i] = j;Numbers[(i + 1) % 4] = Numbers[(i + 2) % 4] = Numbers[(i + 3) % 4] = k;IsOk(y, m, hs);}cout << "count: " << y * m * hs << endl;Count += y * m * hs;// 组合}}cout << Count;return 0;}void IsOk(int &y, int &m, int &hs){int year = Numbers[0] * 1000 + Numbers[1] * 100 + Numbers[2] * 10 + Numbers[3];int month = Numbers[0] * 10 + Numbers[1];int day = Numbers[2] * 10 + Numbers[3];int hour = month;int minute = day;if (year > 0){++y;cout << "Year:" << year << ",";}if (month > 0 && month < 13 && day > 0 && day < 31){++m;cout << "MonthDay:" << month << "-" << day << ",";}if (hour > 0 && hour < 25 && minute >= 0 && minute < 60){++hs;cout << "HourMinute:" << hour << ":" << minute;}cout << endl;}
运行结果
共 212 种组合
0111-01-11 01:11
0111-01-11 10:11
0111-01-11 11:01
0111-01-11 11:10
0111-10-11 01:11
0111-10-11 10:11

Year:111,MonthDay:1-11,HourMinute:1:11Year:1011,MonthDay:10-11,HourMinute:10:11Year:1101,MonthDay:11-1,HourMinute:11:1Year:1110,MonthDay:11-10,HourMinute:11:10count: 64Year:222,MonthDay:2-22,HourMinute:2:22Year:2022,HourMinute:20:22Year:2202,HourMinute:22:2Year:2220,HourMinute:22:20count: 16...Year:1222,MonthDay:12-22,HourMinute:12:22Year:2122,HourMinute:21:22Year:2212,HourMinute:22:12Year:2221,HourMinute:22:21count: 16...Year:2111,HourMinute:21:11Year:1211,MonthDay:12-11,HourMinute:12:11Year:1121,MonthDay:11-21,HourMinute:11:21Year:1112,MonthDay:11-12,HourMinute:11:12count: 48...Year:3111,Year:1311,HourMinute:13:11Year:1131,HourMinute:11:31Year:1113,MonthDay:11-13,HourMinute:11:13count: 12...Year:4111,Year:1411,HourMinute:14:11Year:1141,HourMinute:11:41Year:1114,MonthDay:11-14,HourMinute:11:14count: 12...Year:5111,Year:1511,HourMinute:15:11Year:1151,HourMinute:11:51Year:1115,MonthDay:11-15,HourMinute:11:15count: 12...Year:6111,Year:1611,HourMinute:16:11Year:1161,Year:1116,MonthDay:11-16,HourMinute:11:16count: 8...Year:7111,Year:1711,HourMinute:17:11Year:1171,Year:1117,MonthDay:11-17,HourMinute:11:17count: 8...Year:8111,Year:1811,HourMinute:18:11Year:1181,Year:1118,MonthDay:11-18,HourMinute:11:18count: 8...Year:9111,Year:1911,HourMinute:19:11Year:1191,Year:1119,MonthDay:11-19,HourMinute:11:19count: 8...212