Java Program to Check Armstrong Number

An Armstrong number is a number that is equal to the sum of its digits each raised to the power of the number of digits.

For example, 153 is an Armstrong number because 1³ + 5³ + 3³ = 153.

1. Understanding the Problem

Determine whether a given number is an Armstrong number.

Number: 153 → Armstrong
Number: 9474 → Armstrong
Number: 123 → Not Armstrong

2. Using Basic Loop

Java
Check Armstrong number using loop
import java.util.Scanner;

public class ArmstrongNumber {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = sc.nextInt();

        int original = num;
        int result = 0;
        int digits = String.valueOf(num).length();

        while (num != 0) {
            int remainder = num % 10;
            result += Math.pow(remainder, digits);
            num /= 10;
        }

        if (result == original)
            System.out.println("Armstrong Number");
        else
            System.out.println("Not an Armstrong Number");
    }
}

3. Optimized Approach

Java
Check Armstrong number without converting to string
import java.util.Scanner;

public class ArmstrongOptimized {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = sc.nextInt();

        int original = num;
        int temp = num;
        int digits = 0;

        while (temp != 0) {
            digits++;
            temp /= 10;
        }

        int result = 0;

        while (num != 0) {
            int remainder = num % 10;
            result += Math.pow(remainder, digits);
            num /= 10;
        }

        if (result == original)
            System.out.println("Armstrong Number");
        else
            System.out.println("Not an Armstrong Number");
    }
}

4. Common Mistakes

1. Not calculating the correct number of digits.

2. Forgetting to store the original number before modifying it.

3. Using incorrect power calculation.

4. Not handling single-digit numbers properly.

5. Applications

1. Used in mathematical problem solving.

2. Common example in learning loops and number manipulation.

3. Frequently asked in programming interviews.

Conclusion

Checking Armstrong numbers helps in understanding loops and digit extraction.

Using optimized approaches improves efficiency and avoids unnecessary conversions.