TechByteByByte

Reverse a Number / Check if a Number is a Palindrome - Java

A medium QA/automation coding interview question: reverse a Number / Check if a Number is a Palindrome, with a full Java walkthrough, dry run, and common interviewer follow-ups.

#Math#Loops#Overflow Handling#Medium#Java

Category: Medium | Concepts used: Modulo/division digit extraction, overflow checks


Problem Statement

Part A: Reverse the digits of an integer. Part B: Using that, check if the number is a palindrome (reads the same forwards and backwards).

Input : 12345      Reversed: 54321
Input : 121         Reversed: 121   -> Palindrome!
Input : -121         Reversed: -121  -> Careful with the sign!

Examples (with edge scenarios)

#InputReversedPalindrome?Why
11234554321NoDigits don’t mirror
2121121YesReads the same both ways
3-121-121NoThe - sign itself isn’t “reversible” in the usual sense — most definitions say negative numbers are never palindromes
400YesTrivially the same
512021NoTrailing zero disappears when reversed — 120 reversed is 21, not 021

Common Fresher Mistake

MistakeWhat happensFix
Not handling negative numbersReversing -121 digit-by-digit naively could produce confusing results or an incorrect signDecide up front: negative numbers are typically not palindromes by convention — handle this explicitly
Ignoring potential overflow when reversing large numbersReversing a number near Integer.MAX_VALUE can overflow into garbage or a negative numberUse long during the reversal process to safely detect overflow before casting back to int

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: Peeling and Rebuilding a Tower of Blocks

Imagine you have a tower of labeled blocks (e.g., [1, 2, 3] from top to bottom) and you want to build a reversed tower:

  • You can only access the top block (the rightmost digit, using n % 10):
    • You peel off the top block 3 (lastDigit = n % 10).
    • You place it as the base of your new reversed tower (reversed = 0 * 10 + 3 = 3).
    • Your remaining tower is now shorter: [1, 2] (num /= 10).
  • You repeat this process:
    • Peel off 2 from the top of the remaining tower.
    • To make room for it on the reversed tower, you multiply the current base by 10 (shifting it up: 3 * 10 = 30) and place 2 on top (reversed = 30 + 2 = 32).
    • Your remaining tower is now just [1].
  • You peel off the last block 1.
    • Shift your reversed tower up (32 * 10 = 320) and place 1 on top (reversed = 320 + 1 = 321).
  • You have successfully reversed the block tower using only top-peeling and shifting!

Solution 1 — Reverse Digits Using Modulo and Division

Intuition

Just like extracting digits for a digit-sum problem, n % 10 peels off the last digit, and n / 10 shrinks the number. But this time, instead of adding digits to a sum, we build up a new number by shifting our running result left (multiply by 10) and adding each newly peeled digit — effectively building the number in reverse, one digit at a time.

public class ReverseNumber {
    public static long reverseNumber(int n) {
        boolean isNegative = n < 0;
        long num = Math.abs((long) n); // use long to avoid overflow issues during processing
        long reversed = 0;

while (num > 0) {
            int lastDigit = (int) (num % 10);
            reversed = reversed * 10 + lastDigit; // shift left, add new digit
            num /= 10;
        }

return isNegative ? -reversed : reversed;
    }

public static void main(String[] args) {
        System.out.println(reverseNumber(12345)); // 54321
        System.out.println(reverseNumber(121));    // 121
        System.out.println(reverseNumber(-121));    // -121
        System.out.println(reverseNumber(120));      // 21
    }
}

Output:

54321
121
-121
21

Dry Run (n = 120)

isNegative = false, num=120, reversed=0

lastDigit=120%10=0, reversed=0*10+0=0, num=120/10=12
lastDigit=12%10=2,  reversed=0*10+2=2, num=12/10=1
lastDigit=1%10=1,   reversed=2*10+1=21, num=1/10=0

Final: reversed=21  (leading zero from original trailing zero naturally disappears)

Interviewer’s take

This is the expected digit-manipulation solution — correctly using long internally to avoid overflow, and handling the sign separately from the digit-reversal logic. This overflow-awareness is exactly what interviewers look for, since reversing a number close to Integer.MAX_VALUE is a classic trap.

Follow-up questions you might get:

  • “Why use long instead of int during the process?” → Reversing certain large int values can produce a result that exceeds Integer.MAX_VALUE, silently overflowing if kept as int; using long internally lets you detect (or simply hold) values beyond the normal int range safely.
  • “How would you detect overflow if the final result must be an int?” → After computing with long, compare against Integer.MAX_VALUE/MIN_VALUE before casting back down, and handle the overflow case explicitly (e.g., return 0 or throw an exception, depending on requirements).

Solution 2 — Check Palindrome Using the Reversal (Part B)

Intuition

Since we already know how to reverse a number, checking if it’s a palindrome is simple: reverse it, and compare the reversed version to the original. If they match, it’s a palindrome — reusing Solution 1 as a building block, just like we reused string-reversal logic for string palindromes earlier.

public class NumberPalindromeCheck {

public static long reverseNumber(long n) {
        long reversed = 0;
        while (n > 0) {
            reversed = reversed * 10 + (n % 10);
            n /= 10;
        }
        return reversed;
    }

public static boolean isPalindrome(int n) {
        if (n < 0) {
            return false; // negative numbers are not considered palindromes by convention
        }
        return n == reverseNumber(n);
    }

public static void main(String[] args) {
        System.out.println(isPalindrome(121));  // true
        System.out.println(isPalindrome(123));   // false
        System.out.println(isPalindrome(-121));   // false
        System.out.println(isPalindrome(0));       // true
    }
}

Output:

true
false
false
true

Dry Run (n = 121)

n < 0? no
reverseNumber(121):
  reversed=0*10+1=1, n=12
  reversed=1*10+2=12, n=1
  reversed=12*10+1=121, n=0
  returns 121

121 == 121? -> true

Interviewer’s take

Correct and simple, reusing the reversal logic cleanly. One important design decision to state clearly: negative numbers are treated as non-palindromes by convention (since the negative sign would need to “reverse” too, which doesn’t make sense) — always mention this assumption out loud.

Follow-up questions you might get:

  • “Can you check this without fully reversing the number?” → Advanced follow-up: compare digits from both ends inward (similar to the two-pointer string palindrome technique), or reverse only “half” the number and compare halves — more efficient but more complex to implement correctly. Mentioning awareness of this is a bonus, though the full-reversal approach is usually accepted as sufficient.

📊 Visual Flowchart

graph TD
    Start["Input: Integer n"] --> NegCheck{"n < 0?"}
    NegCheck -->|Yes| AbsVal["isNegative = true<br>num = abs(n)"]
    NegCheck -->|No| AbsValN["isNegative = false<br>num = n"]
    AbsVal --> Loop{"num > 0?"}
    AbsValN --> Loop
    Loop -->|Yes| Peel["lastDigit = num % 10"]
    Peel --> Shift["reversed = reversed * 10 + lastDigit"]
    Shift --> Div["num /= 10"]
    Div --> Loop
    Loop -->|No| Sign["isNegative == true?"]
    Sign -->|Yes| RetNeg["Return -reversed"]
    Sign -->|No| RetPos["Return reversed"]

Final Verdict — Which Solution Should You Give?

  • Solution 1 (reverse with overflow handling) is the expected core technique.
  • Solution 2 (palindrome check via reversal) is the natural extension — correct and clean.
  • Explicitly stating your assumption about negative numbers not being palindromes is a strong signal of careful, communicative thinking — valuable for QA roles.

Quick Recap

PartApproachTimeSpace
Reverse numberModulo + division, using long to avoid overflowO(d) — d = number of digitsO(1)
Palindrome checkReverse and compareO(d)O(1)
Author
TechByteByByte Editorial Team
Reviewed by
TechByteByByte Admin
Published
Last reviewed