TechByteByByte

Check Armstrong Number - Java

A medium QA/automation coding interview question: check Armstrong Number, with a full Java walkthrough, dry run, and common interviewer follow-ups.

#Math#Loops#Medium#Java

Category: Medium | Concepts used: Digit extraction, power computation


Problem Statement

An Armstrong number (also called a narcissistic number) is a number that equals the sum of its own digits, each raised to the power of the number of digits.

Input : 153      Output: true    (1³+5³+3³ = 1+125+27 = 153)
Input : 123       Output: false

Examples (with edge scenarios)

#Input# digitsCalculationOutputWhy
115331³+5³+3³ = 153trueMatches itself
212331³+2³+3³ = 1+8+27=36falseDoesn’t match
39 (single digit)19¹ = 9trueEvery single-digit number is trivially an Armstrong number
4010¹ = 0trueEdge case, treated as single-digit
59474 (4 digits)49⁴+4⁴+7⁴+4⁴ = 9474trueWorks for any digit count, not just 3

Common Fresher Mistake

MistakeWhat happensFix
Hardcoding the power as 3 (assuming only 3-digit Armstrong numbers exist)Fails for numbers with different digit counts (e.g., 4-digit Armstrong numbers like 9474)First count the number of digits in the input, then use THAT as the power
Not handling 0 as a special/edge caseMay cause a divide-by-zero-like error in a “count digits” helper if not careful0 has exactly 1 digit — handle this explicitly if your digit-counting logic assumes n > 0

Before You Code: Clarify the Contract

Before choosing an algorithm, confirm whether zero and negative values are allowed, how large the input can be, and what should happen when an arithmetic result exceeds the chosen Java type. The examples use the contract stated in this article, but an interview answer should say these assumptions aloud.

Analogy: The Committee of Digits

Imagine a team of numbers joining forces to form a single larger number (like 1, 5, and 3 joining to form 153):

  • Before they can declare themselves an Armstrong Number, they must pass a self-identity check:
    • First, they count how many members are in their group (digitCount = 3).
    • Next, each member must go into a chamber and multiply their value by themselves digitCount times (raising to the power of 3).
    • The results are added together:
      • Member 1 yields 1 * 1 * 1 = 1.
      • Member 5 yields 5 * 5 * 5 = 125.
      • Member 3 yields 3 * 3 * 3 = 27.
    • Finally, they sum these chamber results: 1 + 125 + 27 = 153.
    • Because the sum of their powered contributions matches their combined identity (153), they are officially certified as an Armstrong Number!

Solution 1 — Count Digits First, Then Check the Sum

Intuition

The definition specifically says “raised to the power of the number of digits” — so before we can compute anything, we first need to know exactly how many digits the number has. Once we know that count, we extract each digit (same peeling technique as digit-sum/reverse-number problems) and raise it to that fixed power, accumulating the total.

public class ArmstrongNumber {

private static int countDigits(int n) {
        if (n == 0) return 1; // special case: 0 has exactly one digit
        int count = 0;
        while (n > 0) {
            count++;
            n /= 10;
        }
        return count;
    }

public static boolean isArmstrong(int n) {
        int digitCount = countDigits(n);
        int original = n;
        long sum = 0; // use long to be safe from overflow with larger numbers

while (n > 0) {
            int digit = n % 10;
            sum += Math.pow(digit, digitCount);
            n /= 10;
        }

return sum == original;
    }

public static void main(String[] args) {
        System.out.println(isArmstrong(153));  // true
        System.out.println(isArmstrong(123));   // false
        System.out.println(isArmstrong(9));      // true
        System.out.println(isArmstrong(9474));    // true
    }
}

Output:

true
false
true
true

Dry Run (n = 153)

digitCount = countDigits(153) = 3
original = 153, sum=0

digit=153%10=3, sum=0+3³=27, n=153/10=15
digit=15%10=5,  sum=27+5³=27+125=152, n=15/10=1
digit=1%10=1,   sum=152+1³=153, n=1/10=0

sum=153, original=153 -> equal -> true

Interviewer’s take

This is exactly the expected approach — the crucial detail is computing the digit count dynamically rather than hardcoding 3 (which only works for exactly 3-digit inputs). This is precisely the kind of “hidden assumption” trap interviewers plant to see if candidates think through the general definition rather than pattern-matching to the most commonly seen example (153).

Follow-up questions you might get:

  • “Why not just hardcode the power as 3, since 153 is the most common example?” → Because Armstrong numbers exist with different digit counts (e.g., 9474 has 4 digits) — hardcoding would silently give wrong answers for those.
  • “Why Math.pow() and not manual multiplication?”Math.pow() is fine and readable here; some interviewers might ask you to write a manual power function too, to avoid the floating-point conversion Math.pow() does internally (it returns a double) — worth mentioning as a possible precision concern for very large numbers.

Solution 2 — Using a Manual Power Function (Avoids Math.pow() Floating-Point Concerns)

Intuition

Math.pow() works with doubles internally, which can introduce tiny floating-point precision errors for certain values. Since we’re only ever raising small integers (digits 0-9) to small integer powers, we can compute the power manually using a simple loop, staying entirely in integer arithmetic and avoiding any floating-point risk.

public class ArmstrongNumberManualPower {

private static long power(int base, int exponent) {
        long result = 1;
        for (int i = 0; i < exponent; i++) {
            result *= base;
        }
        return result;
    }

private static int countDigits(int n) {
        if (n == 0) return 1;
        int count = 0;
        while (n > 0) {
            count++;
            n /= 10;
        }
        return count;
    }

public static boolean isArmstrong(int n) {
        int digitCount = countDigits(n);
        int original = n;
        long sum = 0;

while (n > 0) {
            int digit = n % 10;
            sum += power(digit, digitCount);
            n /= 10;
        }

return sum == original;
    }

public static void main(String[] args) {
        System.out.println(isArmstrong(153)); // true
        System.out.println(isArmstrong(9474)); // true
    }
}

Output:

true
true

Interviewer’s take

A nice, precision-safe alternative — shows attention to detail about Math.pow()’s floating-point nature, though in practice for small digit values (0-9) and small exponents, Math.pow() is perfectly safe and this level of caution usually isn’t strictly necessary. Good to mention as an awareness point rather than something you must always do.


📊 Visual Flowchart

graph TD
    Start["Input: Integer n"] --> Count["digitCount = countDigits(n)"]
    Count --> Init["original = n<br>sum = 0"]
    Init --> Loop{"n > 0?"}
    Loop -->|Yes| Peel["digit = n % 10"]
    Peel --> Power["term = digit ^ digitCount"]
    Power --> AddSum["sum = sum + term"]
    AddSum --> Div["n /= 10"]
    Div --> Loop
    Loop -->|No| CheckEqual{"sum == original?"}
    CheckEqual -->|Yes| RetTrue["Return True (Armstrong)"]
    CheckEqual -->|No| RetFalse["Return False"]

Final Verdict — Which Solution Should You Give?

  • Solution 1 (with Math.pow()) is perfectly acceptable and commonly expected.
  • The real differentiator interviewers look for is not hardcoding the power — dynamically computing the digit count first is the key insight, regardless of which power-computation method you use.
  • Solution 2 is a nice bonus for precision-mindedness, but not required.

Quick Recap

ApproachTimeSpaceInterview Signal
Digit count + Math.pow()O(d) — d = digit countO(1)Standard, correct
Digit count + manual power loopO(d²) worst case (power loop nested)O(1)Extra precision-safety awareness
Author
TechByteByByte Editorial Team
Reviewed by
TechByteByByte Admin
Published
Last reviewed