要查找两个整数之间的所有 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()
函数内的屏幕上。