问题描述
如果一个日期中年月日的各位数字之和是完全平方数,则称为一个完全日期。
例如:2021 20212021 年 6 66 月 5 55 日的各位数字之和为 2 + 0 + 2 + 1 + 6 + 5 = 16 2 + 0 + 2 + 1 + 6 + 5 = 162+0+2+1+6+5=16,而 16 1616 是一个完全平方数,它是 4 44 的平方。所以 2021 20212021 年 6 66 月 5 55 日是一个完全日期。
例如:2021 20212021 年 6 66 月 23 2323 日的各位数字之和为 2 + 0 + 2 + 1 + 6 + 2 + 3 = 16 2 + 0 + 2 + 1 + 6 + 2 + 3 = 162+0+2+1+6+2+3=16,是一个完全平方数。所以 2021 20212021 年 6 66 月 23 2323 日也是一个完全日期。
请问,从 2001 20012001 年 1 11 月 1 11 日到 2021 20212021 年 12 1212 月 31 3131 日中,一共有多少个完全日期?
思路
使用Java提供的LocalDate类进行解析,在不到万不得已的情况下不要自己写时间类,很容易出错的。大佬无视。
详细的使用方法:🔗博客链接
LocalDate
一般用来出来日期,如果需要处理时间,可以使用Date
或者LocalTime
,如果两者都需要,那么使用LocalDateTime
即可。
代码
package guosai_2021;
import java.time.LocalDate;
public class Perfice {
static LocalDate start = LocalDate.of(2001,01,01);
static LocalDate end = LocalDate.of(2021, 12, 31);
public static void main(String[] args) {
// TODO Auto-generated method stub
// 通过Java提供的本地函数进行求解
long count = 0L;
while(end.compareTo(start) >= 0) {
count += calc(start) ? 1 : 0;
start = start.plusDays(1);
System.out.println(start);
}
System.out.println(count);
}
public static boolean calc(LocalDate date) {
int[] arr = new int[] {
date.getYear(),
date.getMonthValue(),
date.getDayOfMonth()
};
int digit = 0;
for(int d: arr) {
while(d != 0) {
digit += d % 10;
d /= 10;
}
}
return Math.sqrt(digit) % 1 == 0; // 判断是否为整数
}
}