思路:
只有以0、1、5、6结尾的才可能是自守数。
判断方法:把对应数及其平方转为字符串,截取其平方最后对应位数的字符串与原数比较,相等则为自守数。
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
int n = sc.nextInt();
int five_end = 5;
int one_end = 1;
int six_end = 6;
int zero_end = 0;
int count = 0;
if(n == 0){
System.out.println(1);
}else if(n == 1){
System.out.println(2);
}
for(int i = 6; i < n; i += 10){
if(judge(zero_end)){
count++;
}
if(judge(one_end)){
count++;
}
if(judge(five_end)){
count++;
}
if(judge(i)){
count++;
}
zero_end += 10;
one_end += 10;
five_end += 10;
}
System.out.println(count);
}
}
public static boolean judge(int n){
String pow =Integer.toString(n * n);
String self = Integer.toString(n);
int index = pow.length() - self.length();
if(pow.substring(index).equals(self)){
return true;
}
return false;
}
}
京公网安备 11010502036488号