Skip to main content

Number Programs in Java: Reverse, Palindrome, Armstrong, Perfect and Strong Numbers

Reverse a number, palindrome, Armstrong, perfect and strong numbers in Java, each with a dry-run table, real output and the int-overflow trap in reversing.

Five classic number programs, one page: reverse a number, check a palindrome, an Armstrong number, a perfect number and a strong number. They all use the same trick, peeling digits off with % 10 and / 10, so once you have seen it in the reverse program the other four are variations.

ProgramTestExampleNumbers up to 10,000 (or the stated limit)
Reversedigits taken from the end1234 → 4321—
Palindromenumber equals its reverse121—
Armstrongsum of each digit(digit count) equals the number153 = 1³+5³+3³1–9, 153, 370, 371, 407, 1634, 8208, 9474
Perfectproper divisors add up to the number28 = 1+2+4+7+146, 28, 496, 8128
Strongsum of digit factorials equals the number145 = 1!+4!+5!1, 2, 145, 40585 (up to 100,000)
Tested on OpenJDK 21.0.12. The lists in the table were produced by the program and re-checked with an independent brute-force script. Source: NumberPrograms.java. Two more digit-based numbers have their own pages: Disarium numbers and Pronic numbers.

Reverse a number

Take the last digit with n % 10, shift the reversed number one place left (rev * 10) and add the digit, then drop the digit from n with n / 10. Repeat until n is 0.

1234start: n = 1234, rev = 01234step 1: digit 4 leaves n4rev = 443step 2: digit 3 moves across: rev = 434321step 4: rev = 4321 and n = 0

The picture follows 1234: each pass moves one digit from the right end of n to the right end of rev, so the order flips.

static int reverse(int n) {
    int rev = 0;
    while (n != 0) {
        int digit = n % 10;          // last digit
        rev = rev * 10 + digit;      // append it to the reversed number
        n /= 10;                     // drop it from n
    }
    return rev;
}

Source: NumberPrograms.java.

Dry run for 1234, copied from the program output:

Stepn (after)digitrev
112344
212343
312432
4014321
step   n      digit  rev
1      123    4      4
2      12     3      43
3      1      2      432
4      0      1      4321
reverse(1234) = 4321, reverse(120) = 21, reverse(-45) = -54

Source: NumberPrograms.java, method reverse. Trailing zeros disappear (120 becomes 21) and the sign carries through (-45 becomes -54), as the last output line shows.

The int overflow trap in reverse

Reversing a valid int can produce a number that is not a valid int. 1,999,999,999 reversed is 9,999,999,991, which is larger than Integer.MAX_VALUE. In the run above the int version silently printed 1410065399, while the long version gave the right answer. The same issue appears in adding two integers without overflow.

static long reverseLong(long n) {
    long rev = 0;
    while (n != 0) {
        rev = rev * 10 + n % 10;
        n /= 10;
    }
    return rev;
}
reverse(1_999_999_999)     = 1410065399   <- int overflow
reverseLong(1_999_999_999) = 9999999991

Source: NumberPrograms.java.

Palindrome number

A number is a palindrome if it equals its own reverse. Negative numbers are not palindromes here (the minus sign would have to read the same backwards). Use the long reverse to stay safe from the overflow above.

static boolean isPalindrome(int n) {
    if (n < 0) return false;
    return n == reverseLong(n);
}
isPalindrome(121) = true
isPalindrome(123) = false
isPalindrome(1221) = true
isPalindrome(10) = false
isPalindrome(7) = true
isPalindrome(-121) = false

Source: NumberPrograms.java, method isPalindrome.

Armstrong number

A number is Armstrong when the sum of each digit raised to the number of digits equals the number itself. For 153 there are three digits, so 1³ + 5³ + 3³ = 1 + 125 + 27 = 153. Note the power depends on the digit count: 1634 uses fourth powers.

static boolean isArmstrong(int n) {
    int digits = String.valueOf(n).length();
    int sum = 0;
    for (int t = n; t > 0; t /= 10) {
        sum += (int) Math.pow(t % 10, digits);
    }
    return sum == n;
}

Source: NumberPrograms.java.

DigitPowerDigitpowerRunning sum
332727
53125152
131153
digit    power  value    sum
3        3      27       27
5        3      125      152
1        3      1        153
Armstrong numbers 1..10000: [1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474]
isArmstrong(154) = false

Source: NumberPrograms.java, method isArmstrong. The program lists every Armstrong number up to 10,000.

Perfect number

A number is perfect when its proper divisors (all divisors except the number itself) add up to the number. 6 = 1 + 2 + 3 and 28 = 1 + 2 + 4 + 7 + 14. Divisors come in pairs, so you only need to loop up to √n and add both i and n / i. That is why the dry run stops at 5 for 28.

static boolean isPerfect(int n) {
    if (n < 2) return false;
    int sum = 1;                                   // 1 divides everything
    for (int i = 2; (long) i * i <= n; i++) {
        if (n % i == 0) {
            sum += i;
            if (i != n / i) sum += n / i;          // the paired divisor
        }
    }
    return sum == n;
}

Source: NumberPrograms.java.

i28 % iRunning sum
101
2017
3117
4028
5328
i    28 % i     running sum
1    0          1
2    0          17
3    1          17
4    0          28
5    3          28
Perfect numbers 1..10000: [6, 28, 496, 8128]

Source: NumberPrograms.java, method isPerfect. At i = 2 the sum jumps from 1 to 17 because both 2 and its partner 14 were added; at i = 4 it reaches 28 with 4 and 7.

Strong number

A number is strong when the sum of the factorials of its digits equals the number. 145 = 1! + 4! + 5! = 1 + 24 + 120. Precompute 0! to 9! once instead of recalculating a factorial per digit.

static boolean isStrong(int n) {
    int[] fact = new int[10];
    fact[0] = 1;
    for (int i = 1; i < 10; i++) fact[i] = fact[i - 1] * i;   // 0! .. 9!
    int sum = 0;
    for (int t = n; t > 0; t /= 10) sum += fact[t % 10];
    return sum == n;
}

Source: NumberPrograms.java.

DigitDigit!Running sum
5120120
424144
11145
digit    digit!     sum
5        120        120
4        24         144
1        1          145
Strong numbers 1..100000: [1, 2, 145, 40585]

Source: NumberPrograms.java, method isStrong. 1 and 2 qualify because 1! = 1 and 2! = 2; the largest is 40585.

Where to go next

Common interview questions

How do you reverse a number in Java without converting it to a String?

Loop while n != 0: rev = rev * 10 + n % 10; n /= 10;. Use long for rev to avoid overflow.

How do you check a palindrome number?

Reverse it and compare with the original. For non-negative numbers only; or compare the string with its reverse.

What is an Armstrong number?

A number equal to the sum of its digits each raised to the power of the digit count: 153, 370, 371, 407, 1634.

What is the difference between Armstrong and Disarium numbers?

Armstrong raises every digit to the same power (the digit count). Disarium raises each digit to its position.

What is a perfect number and how do you find one efficiently?

A number equal to the sum of its proper divisors. Loop to the square root and add each divisor with its pair.

Common mistakes

  • Modifying the original n and then comparing against it. Copy it first (int t = n) before the digit loop.
  • Using Math.pow and not noticing it returns double. The cast is safe for these ranges but compare integers, not doubles.
  • Forgetting that n % 10 is negative for negative numbers. Handle the sign first, or reject negatives.
  • Adding the pair divisor twice for perfect squares: for 36, i = 6 and n / i = 6 are the same divisor.
  • Counting 1 as a perfect number. Its only proper divisor sum is 0.

FAQ

How do I reverse a number in Java?

Use a while loop with % 10 and / 10. See the dry run above.

How do I check if a number is a palindrome in Java?

Reverse the number using a long and compare with the original.

How do I find Armstrong numbers between 1 and 1000?

For each number, sum each digit raised to the digit count. The answers are 1 to 9, 153, 370, 371 and 407.

What are the perfect numbers below 10,000?

6, 28, 496 and 8128.

What are the strong numbers?

1, 2, 145 and 40585 are the only ones up to 100,000, which is the range the program above checks exhaustively.

Further reading

No Comments yet!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.