下面是我获得三位数Armstrong number的代码:
public class test {
public static void main(String args[]) {
for (int i = 100; i <= 999; i++) {
int firstDigit = (i / 100);
int secondDigit = (i % 100) / 10;
int thirdDigit = (i % 10);
if ((firstDigit * firstDigit * firstDigit)
+ (secondDigit * secondDigit * secondDigit)
+ (thirdDigit * thirdDigit * thirdDigit) == i) {
System.out.println("this is a armstriong number - " + i);
}
}
}
}
我试图得到任何数字阿姆斯特朗根据用户的输入,但我正在结束写太多的循环和多余的代码。
最佳答案
下面的代码检查扫描的号码(在控制台上)是否是armstrong号码。我已经测试过了,效果很好。
控制台测试
import java.util.Scanner;
class ArmstrongNumber
{
public static void main(String args[])
{
int n, sum = 0, temp, remainder, digits = 0;
Scanner in = new Scanner(System.in);
System.out.println("Input a number to check if it is an Armstrong number");
n = in.nextInt();
temp = n;
// Count number of digits
while (temp != 0) {
digits++;
temp = temp/10;
}
temp = n;
while (temp != 0) {
remainder = temp%10;
sum = sum + power(remainder, digits);
temp = temp/10;
}
if (n == sum)
System.out.println(n + " is an Armstrong number.");
else
System.out.println(n + " is not an Armstrong number.");
}
static int power(int n, int r) {
int c, p = 1;
for (c = 1; c <= r; c++)
p = p*n;
return p;
}
}
Source here。
有功能的
如果你需要使用它作为一个功能,请尝试这个
n
参数是要检查的号码。如果我的函数是阿姆斯特朗数,则返回true,否则返回false。public boolean isArmstrongNumber(int n) {
int sum = 0, temp = n, remainder, digits = 0;
while (temp != 0) {
digits++;
temp = temp/10;
}
temp = n;
while (temp != 0) {
remainder = temp%10;
sum = sum + power(remainder, digits);
temp = temp/10;
}
if (n == sum) //Armstrong number
return true;
else //Not Armstrong number
return false;
}
关于java - Java任意数字的阿姆斯特朗号,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37812667/