简体   繁体   English

Java 中的阿姆斯壮编号检查器

[英]Armstrong Number Checker in Java

I am still somewhat of a beginner to Java, but I need help with my code.我仍然是 Java 的初学者,但我的代码需要帮助。 I wanted to write an Armstrong Number checker.我想写一个阿姆斯壮数字检查器。

An Armstrong number is one whose sum of digits raised to the power three equals the number itself.阿姆斯特朗数是一个数字之和,其三的幂等于数字本身。 371, for example, is an Armstrong number because 3^3 + 7^3 + 1^3 = 371.例如,371 是阿姆斯壮数,因为 3^3 + 7^3 + 1^3 = 371。

If I understand this concept correctly, then my code should work fine, but I don't know where I made mistakes.如果我正确理解了这个概念,那么我的代码应该可以正常工作,但我不知道我在哪里犯了错误。 I would appreciate if you could help correct my mistakes, but still kind of stick with my solution to the problem, unless my try is completely wrong or most of it needs to change.如果您能帮助纠正我的错误,我将不胜感激,但仍然坚持我对问题的解决方案,除非我的尝试完全错误或大部分需要更改。

Here is the code:这是代码:

public class ArmstrongChecker {
    
     boolean confirm = false;
     Integer input;
     String converter;
     int indices;
     int result = 1;
    
     void ArmstrongCheck(Integer input) {
        this.input = input;
        converter = input.toString();
        char[] array = converter.toCharArray();
        indices = array.length;
        result = (int) Math.pow(array[0], indices);
        
        for (int i = 1; i < array.length; i++) {
            result = result + (int) Math.pow(array[i], indices);
        }
        if (result == input) {
            confirm = true;
            System.out.println(confirm);
        } else {
            System.out.println(confirm);
        }
    }
}

For my tries I used '153' as an input.对于我的尝试,我使用“153”作为输入。 Thank you for your help!谢谢您的帮助!

You aren't summing the digits, but the numeric values of the characters representing them.您不是对数字求和,而是对代表它们的字符的数值求和。 You can convert such a character to its numeric value by subtracting the character '0' :您可以通过减去字符'0'将此类字符转换为其数值:

int result = 0;
for(int i = 0; i < array.length; i++) {
    result = result + (int) Math.pow(array[i] - '0', indices);
}

Having said that, it's arguably (probably?) more elegant to read the input as an actual int number and iterate its digits by taking the reminder of 10 on each iteration.话虽如此,可以说(可能?)将输入读取为实际的int数字并通过在每次迭代中获取10的提醒来迭代其数字更优雅。 The number of digits itself can be calculated using a base-10 log.位数本身可以使用以 10 为底的对数来计算。

int temp = input;
int result = 0;
int indices = (int) Math.log10(10) + 1;
while (temp != 0) { 
    int digit = temp % 10;
    result += (int) Math.pow(digit, indices);
    temp /= 10;
}

There is a small logical mistake in your code, You're not converting the character to an integer instead you're doing something like您的代码中有一个小逻辑错误,您没有将字符转换为 integer 而是您正在做类似的事情

Math.pow('1', 3) -> Math.pow(49, 3) // what you're doing

Math.pow(1, 3) // what should be done

You should first convert the character to the string using any method below您应该首先使用以下任何方法将字符转换为字符串

result = (int) Math.pow(array[0],indices);

for(int i = 1;i<array.length;i++) {
     result = result + (int) Math.pow(array[i],indices);
}

For converting char to integer用于将 char 转换为 integer

int x = Character.getNumericValue(array[i]);

or或者

int x = Integer.parseInt(String.valueOf(array[i])); 

or或者

int x = array[i] - '0'; 

Alternatively或者

You can also check for Armstrong's number without any conversion, using the logic below您还可以使用以下逻辑检查 Armstrong 的号码,无需任何转换

public class Armstrong {
    public static void main(String[] args) {

        int number = 153, num, rem, res = 0;
        num = number;

        while (num != 0)
        {
            rem = num % 10;
            res += Math.pow(rem, 3);
            num /= 10;
        }

        if(res == num)
            System.out.println("YES");
        else
            System.out.println("NO");
    }
}

For any positive int you can do it like this.对于任何正整数,您都可以这样做。

Print all the Armstrong numbers less than 10_000.打印所有小于 10_000 的 Armstrong 数字。

for (int i = 1; i < 10_000; i++) {
    if (isArmstrong(i)) {
        System.out.println(i);
    }
}

prints印刷

1
2
3
4
5
6
7
8
9
153
370
371
407
1634
8208
9474

The key is to use Math.log10 to compute the number of digits in the candidate number.关键是使用Math.log10来计算候选号的位数。 This must be amended by adding 1. So Math.log10(923) returns 2.965201701025912 .这必须通过添加 1 来修改。所以Math.log10(923)返回2.965201701025912 Casting to an int and adding 1 would be 3 digits .转换为int并添加1将是3 digits The number of digits is then the power used for computation.那么位数就是用于计算的功率。

Then it's just a matter of summing up the digits raised to that power.然后,只需将提升到该幂的数字相加即可。 The method short circuits and returns false if the sum exceeds the number before all the digits are processed.如果在处理所有数字之前总和超过了数字,则该方法会短路并返回false

    
public static boolean isArmstrong(int v) {
    if (v < 1) {
        throw new IllegalArgumentException("Argument must > 0");
    }
    
    int temp = v;
    int power = (int)Math.log10(temp)+1;
    int sum = 0;
    
    while (temp > 0) {
        sum += Math.pow(temp%10, power);
        
        if (sum > v) {
           return false;
        }

        temp/= 10;
    }
    
    return v == sum;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM