← Back to libraryQuestion 76 of 273
⌨️Java CodingIntermediate

Check for an Armstrong Number

📌 Definition:

An Armstrong (narcissistic) number equals the sum of its own digits each raised to the power of the digit count (e.g. 153 = 1^3 + 5^3 + 3^3).

📖 Detailed Explanation:

Count the digits d, then sum each digit raised to the power d and compare to the original number. Extract digits with %10 and /10. O(number of digits) plus the power computations.

💻 Solutions:
public static boolean isArmstrong(int n) {
    int digits = String.valueOf(n).length();
    int sum = 0, temp = n;
    while (temp != 0) {
        int d = temp % 10;
        sum += (int) Math.pow(d, digits);
        temp /= 10;
    }
    return sum == n;
}
function isArmstrong(n) {
  const digits = String(n).length;
  const sum = String(n).split('')
    .reduce((acc, d) => acc + Math.pow(Number(d), digits), 0);
  return sum === n;
}
def is_armstrong(n):
    digits = len(str(n))
    return n == sum(int(d) ** digits for d in str(n))
🔑 Key Points:
  • Raise each digit to the power of the digit COUNT
  • Compare the sum to the original
  • Works for any digit length, not just 3
  • O(digits)
🌍 Real-World Example:

A number-theory exercise that checks digit extraction and careful reading of the definition (power = digit count, not a fixed 3).

🎯 Scenario-Based Interview Question:

A candidate hardcodes the exponent to 3 and it fails for 9474 (a 4-digit Armstrong number). Fix?