Count the digits of the number, then add up each digit raised to the power of that count. If the sum equals the original number, it is an Armstrong number.
public class ArmstrongNumber {
static boolean isArmstrong(int number) {
if (number < 0) return false;
int digits = String.valueOf(number).length();
long sum = 0;
int n = number;
while (n > 0) {
int digit = n % 10;
long power = 1;
for (int i = 0; i < digits; i++) {
power *= digit;
}
sum += power;
n /= 10;
}
return sum == number;
}
public static void main(String[] args) {
int[] tests = {153, 370, 9474, 123, 0};
for (int t : tests) {
System.out.println(t + " is Armstrong: " + isArmstrong(t));
}
}
}153 is Armstrong: true
370 is Armstrong: true
9474 is Armstrong: true
123 is Armstrong: false
0 is Armstrong: true
All Armstrong numbers below 1000 are 0 to 9, 153, 370, 371 and 407; printing the ones in a range is a common variation of this question.
Mention that the exponent is the digit count, using 9474 as the example; many candidates hard-code a cube and only pass for three-digit numbers.
A concise interview answer is
I count the digits, then take each digit with % 10, raise it to the power of the digit count with an integer loop, and add it to a long sum. If the sum equals the original number it is an Armstrong number, which works for any length, like 153 or 9474.
Last updated: 11 November 2026
Previous question: Write a Java program to find the second-highest number in an array.
Next question: Write a Java program to remove all whitespace from a string without using replace() or replaceAll().