主要使用String的endsWith() 方法,用于测试字符串是否以指定的后缀结束。如果参数表示的字符序列是此对象表示的字符序列的后缀,则返回 true;否则返回 false。注意,如果参数是空字符串,或者等于此 String 对象(用 equals(Object) 方法确定),则结果为 true。

/**
 * @Description 自守数
 * @Author haixiaofei
 * @Date 2022/2/23 9:20
 **/
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int n = in.nextInt();
            int count = 0;
            for (int i = 0; i <= n; i++) {
                String str = String.valueOf(i*i);
                String s = String.valueOf(i);
                if (str.endsWith(s)) {
                    count++;
                }
            }
            System.out.println(count);
        }
    }
}