华为机试 HJ99题解 | #自守数# Java实现
自守数
https://www.nowcoder.com/practice/88ddd31618f04514ae3a689e83f3ab8e
思路:很容易想到使用字符串比较,将输入整数n转换成字符串s1,n的平方n*n转换成字符串s2,如果s2是以s1结尾,则为自守数。另外,注意当个位数为0、1、5、6这几种情况才需要进一步判断是否为自守数,其他情况直接PASS。
Java实现代码如下:
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static int CalAutomorphicNumbers(int n) {
int count = 0;
for (int i = 0; i <= n; i++) {
// 仅对个位数为0,1,5,6等符合条件的数执行自守数的判断
if ((i % 10 == 0) || (i % 10 == 1) || (i % 10 == 5) || (i % 10 == 6)) {
long j = i * i;
String s1 = Integer.toString(i); // 25
String s2 = Long.toString(j); // 625
if (s2.endsWith(s1)) {
count++;
}
}
}
return count;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextInt()) { // 注意 while 处理多个 case
int n = in.nextInt();
System.out.println(CalAutomorphicNumbers(n));
}
}
