📌  相关文章
📜  Java程序使用函数显示间隔之间的阿姆斯壮数

📅  最后修改于: 2020-09-26 17:37:26             🧑  作者: Mango

在此程序中,您将学习如何使用Java中的函数显示两个给定间隔(低和高)之间的所有阿姆斯壮数字。

要查找两个整数之间的所有Armstrong数字,将创建checkArmstrong() 函数 。此函数检查数字是否为Armstrong。

示例:两个整数之间的阿姆斯壮数
public class Armstrong {

    public static void main(String[] args) {

        int low = 999, high = 99999;

        for(int number = low + 1; number < high; ++number) {

            if (checkArmstrong(number))
                System.out.print(number + " ");
        }
    }

    public static boolean checkArmstrong(int num) {
        int digits = 0;
        int result = 0;
        int originalNumber = num;

        // number of digits calculation
        while (originalNumber != 0) {
            originalNumber /= 10;
            ++digits;
        }

        originalNumber = num;

        // result contains sum of nth power of its digits
        while (originalNumber != 0) {
            int remainder = originalNumber % 10;
            result += Math.pow(remainder, digits);
            originalNumber /= 10;
        }

        if (result == num)
            return true;

        return false;
    }
}

输出

1634 8208 9474 54748 92727 93084 

在上面的程序中,我们创建了一个名为checkArmstrong()的函数 ,该函数接受一个参数num并返回一个布尔值。

如果数字是Armstrong,则返回true 。如果不是,则返回false

根据返回值,该数字将显示在main() 函数内部的屏幕上。