Approach: The solution first counts the total number of digits in the number. It then extracts each digit, raises it to the power of the digit count, and adds the result to a running sum. If the final sum matches the original number, the number is an Armstrong number.
This approach works for Armstrong numbers of any length and is more flexible than solutions that assume only three-digit numbers.
Java Solution:
public class ArmstrongNumber {
public static boolean isArmstrong(int number) {
int originalNumber = number;
int digitCount = String.valueOf(number).length();
int sum = 0;
while (number > 0) {
int digit = number % 10;
sum += Math.pow(digit, digitCount);
number /= 10;
}
return sum == originalNumber;
}
public static void main(String[] args) {
int number = 153;
if (isArmstrong(number)) {
System.out.println(number + " is an Armstrong Number.");
} else {
System.out.println(number + " is not an Armstrong Number.");
}
}
}Output: 153 is an Armstrong Number.
Time Complexity: O(d), where d is the number of digits in the number. The number is traversed once to process each digit.
Space Complexity: O(1), since only a few additional variables are used regardless of the input size.
Key Interview Points: • An Armstrong number is equal to the sum of its digits raised to the power of the total number of digits. • This implementation supports Armstrong numbers with any number of digits instead of being limited to three-digit numbers. • A common interview follow-up is to print all Armstrong numbers within a given range.