简体   繁体   中英

Armstrong Number Checker in Java

I am still somewhat of a beginner to Java, but I need help with my code. 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.

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. 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' :

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. The number of digits itself can be calculated using a base-10 log.

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

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

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

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.

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. This must be amended by adding 1. So Math.log10(923) returns 2.965201701025912 . Casting to an int and adding 1 would be 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.

    
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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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