首页 > 解决方案 > 如何用Java编写一个强数字函数

问题描述

在此处输入图像描述我正在尝试解决这个问题:

a) 使用以下标头编写一个方法,该方法采用整数 n 并返回 n 的值!(发音为 n 阶乘)计算如下:

public static int factorial(int n)

请注意,0!= 1 和 n! = n * (n-1) * (n-2)*.....*1。示例:factorial(4) 将返回 24,即 = 4*3*2*1。

b) 使用以下标头编写一个方法,该方法采用整数 x 并在 x 是强数字时返回 true。否则,它返回 false。

public static boolean isStrongNumber(int x)

请注意,该isStrongNumber方法应调用阶乘方法来计算 x 中每个数字的阶乘。

public static int factorial(int n) {
    int f =1;
    for (int i = 1; i <=n; i++) 
       f=f*i;

    return f;
}
     public static boolean isStrongNumber(int x) {
        int temp = x;
        int z;
        int q = 0;
        int sum = 0;
        while (temp > 0) {

            x = x % 10;
            z = factorial(x);
            q += z;

            if (q == temp) {
                System.out.print(q + " ");
                return true;

            }
        }

    }

这是我的答案,但每次尝试运行它时都会出错。

标签: java

解决方案


您没有在isStrongNumber方法结束时返回布尔值

     public static int factorial(int n) {
        int result = 1;
        for (int i = 2; i <= n; i++) {
            result *= i;
        }

        return result;
    }

    public static boolean isStrongNumber(int num) {
        int originalNum = num;
        int sum = 0;

        while (num > 0) {
            sum += factorial(num % 10);
            num /= 10;
        }

        return sum == originalNum;
    }

,main函数

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a positive integer: ");
        int number = Integer.parseInt(scanner.nextLine());
        Set<Integer> set = new TreeSet<>();
        for (int i = 1; i <= number; i++) {
            if (isStrongNumber(i)) {
                set.add(i);
            }
        }
        System.out.println("The Strong numbers between 1 and " + number + " are:");
        System.out.println(set);
        scanner.close();
    }

, 输出为输入100000

Enter a positive integer: 100000
The Strong numbers between 1 and 100000 are:
[1, 2, 145, 40585]

推荐阅读