自守數

題目描述

自守數是指一個數的平方的尾數等於該數自身的天然數。例如:252 = 625,762 = 5776,93762 = 87909376。
請求出n之內的自守數的個數

接口說明
     /**
      * 功能: 求出n之內的自守數的個數
      *
      * 輸入參數:int n
      * 返回值:n之內自守數的數量。
      */
     public static int calcAutomorphicNumbers(int n) {
         /*在這裏實現功能*/
         return 0;
     }

輸入描述

int型整數

輸出描述

n之內自守數的數量。

輸入例子

2000

輸出例子

8

算法實現

import java.util.Scanner;

/**
 * All Rights Reserved !!!
 */
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
//        Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt"));
            while (scanner.hasNext()) {
            int n = scanner.nextInt();
            System.out.println(calcAutomorphicNumbers(n));
        }

        scanner.close();
    }

    private static int calcAutomorphicNumbers(int n) {

        int result = 0;

        for (int i = 0; i <= n; i++) {
            if (isAutomorphicNumber(i)) {
                result++;
            }
        }


        return result;
    }

    private static boolean isAutomorphicNumber(int n) {

        int s = n * n;

        while (n != 0) {
            if (s % 10 == n % 10) {
                s /= 10;
                n /= 10;
            } else {
                return false;
            }
        }

        return true;
    }
}
相關文章
相關標籤/搜索