</>

Technology

Java Programs

Difficulty

Intermediate

Interview Question

Write a Java program to check if a number is an Armstrong number (narcissistic number).

Answer

Armstrong Number in Java

Java
public class ArmstrongNumber {
    public static void main(String[] args) {
        int num = 153;
        int original = num;
        int result = 0;

        // Count number of digits
        int digits = String.valueOf(num).length();  // 3

        int temp = num;
        while (temp != 0) {
            int lastDigit = temp % 10;
            result += (int) Math.pow(lastDigit, digits);  // digit^n
            temp /= 10;
        }

        if (result == original)
            System.out.println(original + " is an Armstrong number");
        else
            System.out.println(original + " is NOT an Armstrong number");
    }
}

Output

CODE
153 is an Armstrong number

Step-by-Step for 153

CODE
digits = 3
temp = 153

Iteration 1: lastDigit=3, 3³=27,  result=27,  temp=15
Iteration 2: lastDigit=5, 5³=125, result=152, temp=1
Iteration 3: lastDigit=1, 1³=1,   result=153, temp=0

153 == 153 → Armstrong!

Print All Armstrong Numbers from 1 to 1000

Java
public class PrintAllArmstrong {
    public static void main(String[] args) {
        System.out.print("Armstrong numbers (1-1000): ");

        for (int num = 1; num <= 1000; num++) {
            int digits = String.valueOf(num).length();
            int temp = num, sum = 0;

            while (temp != 0) {
                int d = temp % 10;
                sum  += (int) Math.pow(d, digits);
                temp /= 10;
            }

            if (sum == num) System.out.print(num + " ");
        }
    }
}

Output

CODE
Armstrong numbers (1-1000): 1 2 3 4 5 6 7 8 9 153 370 371 407

Armstrong Numbers Reference

NumberCalculationArmstrong?
1531³+5³+3³ = 153✓ Yes
3703³+7³+0³ = 370✓ Yes
3713³+7³+1³ = 371✓ Yes
4074³+0³+7³ = 407✓ Yes
16341⁴+6⁴+3⁴+4⁴ = 1634✓ Yes
1231³+2³+3³ = 36 ≠ 123✗ No

Follow AutomateQA