Check Armstrong Number in Java

Beginner
⏱️ 12 min read
📚 Updated: May 2026
🎯 2 Code Examples
Digits & powers

What you’ll learn

  • The Armstrong (narcissistic) condition in base 10: sum of each digit raised to the number of digits.
  • A precise algorithm, pseudocode, and two Java programs: one number and a range scan.
  • Why integer exponentiation is safer than Math.pow for exact checks, plus edge cases and complexity.
  • A browser live preview that mirrors the same digit-power rule.

Overview

An Armstrong number equals the sum of its decimal digits, each raised to the power of how many digits it has. Classic example: 153 = 1³ + 5³ + 3³. This tutorial shows how to implement that test in Java, then scan a range.

Two programs

A single-value check (try 153) and a range listing (from 1 to 200 in the sample output).

Live preview

See digit count k, the expanded sum of each dk, and the verdict without compiling.

Interview polish

Guards for n <= 0, integer powers, overflow notes, and complexity in one place.

Prerequisites

Comfort with loops, integer division, and the modulo operator % is enough to follow the code.

  • Java basics: class Main, public static void main(String[] args), methods, and System.out.println.
  • Extracting the last digit with n % 10 and shifting with n / 10.
  • Optional: comparing this idea to amicable and abundant problems (different rules, same “loop over structure of n” pattern).

What is an Armstrong number?

Let n be a positive integer with k decimal digits. Write those digits as dk-1 ... d1 d0 (most significant to least). Then n is an Armstrong number (in base 10) when

dk-1k + ... + d1k + d0k = n.

The exponent is always the digit count, not the digit value. We stay in decimal on this page.

Armstrong sum of (each digit)k = n
Not Armstrong that sum != n
Synonyms narcissistic / PPDI (base 10)

Mathematical definition

Fix base b = 10. If n has k decimal digits ak-1, ..., a0 (most significant to least), then n is Armstrong when ak-1k + ... + a0k = n.

Three-digit template

For 100 <= n <= 999, write n = 100a + 10b + c with digits a,b,c. Armstrong means a³ + b³ + c³ = 100a + 10b + c.

Examples: 153, 370, 371, 407 are the only three-digit Armstrong numbers besides the one-digit cases.

Intuition and examples

Count how many digits n has. Peel digits off from the right with % 10 and / 10, raising each digit to that count and adding into a running total. If the total lands back on n, you have an Armstrong number.

Each card shows the digit-power sum with the same exponent k everywhere.

153 Armstrong
Digits
3, so exponent 3
Sum
1³ + 5³ + 3³ = 1 + 125 + 27 = 153
Verdict
Equals n - Armstrong.
123 Not Armstrong
Digits
3, exponent 3
Sum
1³ + 2³ + 3³ = 1 + 8 + 27 = 36
Verdict
36 != 123 - not Armstrong.
7 Armstrong
Digits
1, exponent 1
Sum
7¹ = 7
Verdict
Every 1-9 works the same way.

Takeaway: the exponent is the length of n in decimal.

Live preview

Type a positive integer n. The widget counts decimal digits k, builds the sum of each digit to the kth power, and compares it to n. Caps at 999 999 999 to keep browser arithmetic predictable.

  1. Try 153, 123, or a single digit.
  2. Press Run check (or Enter).
  3. Read the expanded sum line and the verdict.

Use integers n >= 1. Very large n may hit precision limits in the browser before Java overflow notes matter.

Live result
Press “Run check” to see digit powers and the verdict.

Algorithm

Goal: decide whether a given n is an Armstrong number in base 10.

Validate n

If n <= 0, return false (or follow your problem’s convention explicitly).

Count digits k

Copy n to a temporary variable and repeatedly divide by 10 until it becomes 0, counting iterations.

Accumulate digit powers

Walk digits again with % 10 and / 10. Add digit^k to a running sum using exact integer exponentiation.

Compare

If the sum equals the original n, return true; otherwise false.

📜 Pseudocode

Pseudocode
function digitCount(n):
    k ← 0
    t ← n
    while t > 0:
        k ← k + 1
        t ← floor(t / 10)
    return k

function sumDigitPowers(n, k):
    sum ← 0
    t ← n
    while t > 0:
        d ← t mod 10
        sum ← sum + (d to the power k)   // integer power
        t ← floor(t / 10)
    return sum

function isArmstrong(n):
    if n <= 0:
        return false
    k ← digitCount(n)
    return sumDigitPowers(n, k) = n
1

Check a single number (program with explanation)

Uses a small integer power helper so every step stays in integer arithmetic - no floating-point rounding.

java
public class Main {
    static int ipow(int base, int exp) {
        int r = 1;
        for (int i = 0; i < exp; i++) {
            r *= base;
        }
        return r;
    }

    // Returns true if n is Armstrong (base 10), false otherwise; n > 0 only
    static boolean isArmstrong(int number) {
        if (number <= 0) {
            return false;
        }

        int k = 0;
        int t = number;
        while (t > 0) {
            k++;
            t /= 10;
        }

        t = number;
        int sum = 0;
        while (t > 0) {
            int d = t % 10;
            sum += ipow(d, k);
            t /= 10;
        }

        return sum == number;
    }

    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.");
        }
    }
}

Explanation

Two passes over the digits: first to learn k, second to sum dk for each digit d.

if (number <= 0) return false;

Guard non-positive inputs. This page uses the common convention of checking positive integers only.

while (t > 0) { k++; t /= 10; }

Count digits. Integer division by 10 removes one digit per step.

sum += ipow(d, k);

Same exponent for every digit. That exponent is exactly the digit count k.

return sum == number;

Final comparison against the original value.

2

Armstrong numbers in a range

Same isArmstrong helper as Example 1, wrapped in a loop from 1 to 200.

java
public class Main {
    static int ipow(int base, int exp) {
        int r = 1;
        for (int i = 0; i < exp; i++) {
            r *= base;
        }
        return r;
    }

    static boolean isArmstrong(int number) {
        if (number <= 0) {
            return false;
        }
        int k = 0;
        int t = number;
        while (t > 0) {
            k++;
            t /= 10;
        }
        t = number;
        int sum = 0;
        while (t > 0) {
            int d = t % 10;
            sum += ipow(d, k);
            t /= 10;
        }
        return sum == number;
    }

    public static void main(String[] args) {
        int start = 1;
        int end = 200;
        System.out.println("Armstrong numbers in the range " + start + " to " + end + ":");
        for (int i = start; i <= end; i++) {
            if (isArmstrong(i)) {
                System.out.print(i + " ");
            }
        }
        System.out.println();
    }
}

Optimization

Exponentiation. For fixed digit count k, precompute 0^k ... 9^k in an array of length 10 and replace ipow(d,k) with a lookup when scanning many numbers.

Bounds on sums. For a given k, the maximum digit-power sum is 9^k * k. This can help prune candidates in generators.

Wide integers. Promote the accumulator to long if powers can overflow int.

Interview: state the O(log n) digit pass clearly; mention lookup tables only if asked.

❓ FAQ

In base 10, a positive integer n is an Armstrong number (also called narcissistic) if n equals the sum of its decimal digits, each raised to the power of the total number of digits. Example: 153 has three digits and 1^3 + 5^3 + 3^3 = 153.
Yes. For a one-digit n, the digit count is 1, and n^1 = n, so every digit 1 through 9 is Armstrong. Whether to include 0 depends on the problem statement; this page treats n <= 0 as not Armstrong.
Math.pow uses floating point, which can introduce rounding for some powers. An integer power loop keeps the equality check exact for typical interview constraints.
Definitions vary. The sample programs return false for n <= 0 so digit counting stays consistent and matches common contest specs that only ask for positive integers.
Let d be the number of decimal digits. Counting digits and summing digit powers are both O(d), and d is Theta(log n), so the whole test is O(log n) in base 10.
The sum of digit powers can exceed 32-bit int before you compare to n. Use long for the accumulator (and sometimes for n) when the problem allows large inputs.

🔄 Input / output examples

For the single-number program with a literal number, typical lines look like this. For interactive runs you can read with Scanner.

Value of numberTypical line printed
153153 is an Armstrong number.
123123 is not an Armstrong number.
77 is an Armstrong number.
00 is not an Armstrong number. (with the sample guard)

For the range program with start = 1 and end = 200:

Console
Armstrong numbers in the range 1 to 200:
1 2 3 4 5 6 7 8 9 153

Edge cases and pitfalls

Most bugs come from miscounting digits, reusing a mutated copy of n, or mixing floating-point powers into an integer test.

Input

n <= 0

Return false early. Otherwise 0 can slip through with a digit count of 0 in naive loops.

State

Losing the original n

Keep one variable for comparison and separate temporaries for counting and summing.

Floats

Math.pow rounding

Casting a floating-point power to int can be off by 1 for some values. Prefer integer exponentiation for exact equality.

Overflow

Partial sums

Digit powers add up quickly. Use long when constraints are large.

⏱️ Time and space complexity

TaskTimeExtra space
Single isArmstrong(n) (two digit passes, k = O(log n))O(log n)O(1)
ipow(d, k) per digit (naive multiply loop)O(k) per callO(1)
All n in [1, U] with naive ipowroughly O(U * log^2 U)O(1)
Same range with a fixed table for 0..9 to the power kO(U log U)O(1) table

Auxiliary memory beyond the call stack is a handful of integers in both sample programs.

Summary

  • Definition: sum of each decimal digit raised to the digit-count power equals n.
  • Implementation: count digits, accumulate integer powers, compare to the original n; guard n <= 0 if required.
  • Watch-outs: avoid floating-point rounding, watch overflow on the sum, and keep the original value for the final equality.
Did you know?

Besides the trivial one-digit cases 19, the only three-digit Armstrong numbers are 153, 370, 371, and 407. For example, 1³ + 5³ + 3³ = 153.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful