Introduction

Reversing a number is one of the most common Java programming exercises and a favorite interview question for beginners. Although it appears simple, it helps you understand important concepts such as the modulus operator, integer division, loops, recursion, and string manipulation.

This problem also serves as the foundation for several other programming challenges, including checking whether a number is a palindrome, Armstrong number programs, and various digit-based algorithms.

In this tutorial, you'll learn four different ways to reverse a number in Java, understand how each method works internally, compare their advantages and disadvantages, and explore common interview questions related to reversing numbers.

Advertisement

What Does Reversing a Number Mean?

Reversing a number means changing the order of its digits.

For example:

Original Number : 12345
Reversed Number : 54321

Unlike reversing a string, numbers cannot simply be indexed. Instead, digits must be extracted one at a time and rebuilt in reverse order.


Method 1: Using a While Loop (Modulus and Division)

This is the standard and most commonly used approach.

Java Program

public class Main {

    public static void main(String[] args) {

        int num = 12345;
        int reversed = 0;

        while (num != 0) {
            int digit = num % 10;
            reversed = reversed * 10 + digit;
            num = num / 10;
        }

        System.out.println("Reversed number: " + reversed);
    }
}

Output

Reversed number: 54321

How It Works

During each iteration:

  • % 10 extracts the last digit.

  • reversed * 10 shifts the current reversed number one digit to the left.

  • The extracted digit is appended.

  • / 10 removes the last digit from the original number.

This process continues until the original number becomes zero.

Time Complexity

O(d)

where d is the number of digits.

Space Complexity

O(1)


Method 2: Using Recursion

Instead of using a loop, recursion processes one digit per function call.

Java Program

public class Main {

    static int reversed = 0;

    static void reverse(int num) {

        if (num == 0) {
            return;
        }

        int digit = num % 10;
        reversed = reversed * 10 + digit;

        reverse(num / 10);
    }

    public static void main(String[] args) {

        int num = 1234;

        reverse(num);

        System.out.println("Reversed Number: " + reversed);
    }
}

Output

Reversed Number: 4321

Each recursive call processes one digit until the number becomes zero.

Time Complexity

O(d)

Space Complexity

O(d)

because each recursive call occupies one stack frame.


Method 3: Using StringBuilder.reverse()

Java provides a built-in method to reverse strings.

Java Program

public class Main {

    public static void main(String[] args) {

        int num = 12345;

        String reversedString = new StringBuilder(String.valueOf(num))
                .reverse()
                .toString();

        int reversed = Integer.parseInt(reversedString);

        System.out.println("Reversed number: " + reversed);
    }
}

Output

Reversed number: 54321

This method converts the number into a string, reverses it, and converts it back into an integer.

Time Complexity

O(d)

Space Complexity

O(d)

because a StringBuilder object is created.


Method 4: Handling Negative Numbers

Negative numbers require special handling.

Java Program

public class Main {

    public static void main(String[] args) {

        int num = -123;

        boolean isNegative = num < 0;

        num = Math.abs(num);

        int reversed = 0;

        while (num != 0) {

            int digit = num % 10;
            reversed = reversed * 10 + digit;

            num = num / 10;
        }

        if (isNegative) {
            reversed = -reversed;
        }

        System.out.println("Reversed number: " + reversed);
    }
}

Output

Reversed number: -321

The negative sign is removed before reversing and added back after all digits have been processed.

Time Complexity

O(d)

Space Complexity

O(1)


How Java Handles This Internally

Consider:

int num = 12345;
int reversed = 0;

Internally:

  1. num, digit, and reversed are primitive int variables stored in stack memory.

  2. During every iteration, % 10 extracts the last digit.

  3. / 10 removes the last digit.

  4. The reversed value is rebuilt using multiplication and addition.

  5. In the recursive approach, each recursive call creates a new stack frame.

  6. In the StringBuilder approach, a StringBuilder object is created on the heap.

  7. Once the program finishes, stack variables are automatically removed, and heap objects become eligible for garbage collection.


Real-Life Analogy

Imagine reading a house number painted on a wall from right to left.

For example:

12345

Instead of reading:

1 → 2 → 3 → 4 → 5

you read:

5 → 4 → 3 → 2 → 1

The while-loop method follows this exact approach by repeatedly taking the last digit first.


Comparison of Different Methods

Method Extra Memory Handles Negative Numbers Best Used When
While Loop No With additional logic Interviews and production code
Recursion Uses call stack With additional logic Learning recursion
StringBuilder Yes With additional logic Quick and readable code
While Loop + Sign Handling No Yes Production applications

Best Practices

  • Prefer the arithmetic while-loop approach for interviews and production code.

  • Always handle negative numbers separately.

  • Consider using long when reversing very large integers to avoid overflow.

  • Use StringBuilder.reverse() when readability is more important than performance.

  • Avoid using static variables in recursive solutions when possible.


Common Mistakes

Forgetting to Remove the Last Digit

Incorrect:

digit = num % 10;

without updating:

num = num / 10;

This results in an infinite loop.


Forgetting to Multiply by 10

Incorrect:

reversed = reversed + digit;

The existing digits are never shifted, producing incorrect output.

Always use:

reversed = reversed * 10 + digit;

Ignoring Negative Numbers

Without using Math.abs(), the modulus operator returns negative digits, producing incorrect results.


Assuming StringBuilder Handles Negative Signs

Reversing:

-123

produces:

321-

which cannot be converted back into an integer.

Always remove the sign first.


Ignoring Integer Overflow

Very large numbers may overflow while building the reversed value.

Consider using a long if overflow is possible.


Expert Tips

  • Explain the modulus (%) and division (/) operators clearly during interviews.

  • Mention handling of negative numbers without being prompted.

  • Explain that the algorithm processes one digit at a time.

  • Recommend using the arithmetic approach instead of string conversion when performance matters.


Pros and Cons

Method Advantages Disadvantages
While Loop Fast, memory efficient, interview-friendly Needs manual negative-number handling
Recursion Elegant solution Uses additional stack memory
StringBuilder Short and readable Creates heap objects and requires string conversion
Sign Handling Correct for all integer inputs Slightly more code

Frequently Asked Questions

What is the easiest way to reverse a number in Java?

Use a while loop with the modulus (%) and division (/) operators.


Can I reverse a number without using a loop?

Yes.

Use recursion to process one digit during each function call.


Can I reverse a number using StringBuilder?

Yes.

Convert the number into a string, call .reverse(), and convert the result back into an integer.


How do I reverse a negative number?

Store the sign separately, reverse the absolute value, and then reapply the negative sign.


Can reversing a number cause integer overflow?

Yes.

If the reversed value exceeds the range of an int, overflow occurs.

Using a long helps avoid this issue.


Is StringBuilder slower than the arithmetic approach?

Slightly.

It creates additional objects and performs string conversion.


A palindrome check reverses the number and compares it with the original value.

If both are equal, the number is a palindrome.


What is the time complexity?

Each digit is processed exactly once.

Time Complexity: O(d)

where d is the number of digits.


Can this algorithm reverse numbers in other number systems?

Yes.

Replace base 10 with the required base.

For example:

  • Binary → % 2 and / 2

  • Octal → % 8 and / 8

  • Hexadecimal → % 16 and / 16


Why does the recursive version use a static variable?

The static variable stores the accumulated reversed value across recursive calls.

A cleaner solution is to return the accumulated value instead of relying on shared state.


What happens to trailing zeros?

For example:

1200

becomes:

21

Leading zeros are not stored in integer values.


Is this a common interview question?

Yes.

It is one of the most frequently asked Java interview questions because it tests loops, modulus, division, recursion, and edge-case handling.