顺子日期
小明特别喜欢顺子。顺子指的就是连续的三个数字:123、456 等。顺子日期指的就是在日期的 yyyymmdd 表示法中,存在任意连续的三位数是一个顺子的日期。例如 20220123 就是一个顺子日期,因为它出现了一个顺子:123;而 20221023 则不是一个顺子日期,它一个顺子也没有。小明想知道在整个 2022 年份中,一共有多少个顺子日期。
【思路分析】
2022年一共365天,枚举每一天判断是否存在顺子日期即可
问:如何判断某一年是平年还是闰年?
答:非整百年份能被 4 整除但不能被 100 整除,那这个年份就是闰年,如2004年,整百年份能被 400 整除才是闰年,如2000年
问:如何在枚举过程中实现月份的跳转
答:预处理每个月有多少天
public class Main {
// 定义每个月的天数数组,0 占位
static int[] months = {
0, 31, 28, 31, 30, 31,
30, 31, 31, 30, 31, 30,
31
};
// 检查字符串中是否存在连续递增3个字符的情况
static boolean check(String str) {
for (int i = 0; i + 2 < str.length(); i++) {
if (str.charAt(i + 1) == str.charAt(i) + 1 && str.charAt(i + 2) == str.charAt(i) + 2) {
return true;
}
}
return false;
}
public static void main(String[] args) {
int year = 2022;
int month = 1;
int day = 1;
int res = 0;
for (int i = 0; i < 365; i++) {
String str = String.format("%04d%02d%02d", year, month, day);
if (check(str)) {
res++;
System.out.println(str);
}
day++;
if (day > months[month]) {
day = 1;
month++;
}
}
System.out.println(res);
}
}