1.
Introduction
2.
Algorithm for Reversing a Number in Java
2.1.
Step-by-Step Process
3.
Example
3.1.
Java
4.
Methods to Reverse a Number in Java
5.
Using While Loop
5.1.
How it Works
5.2.
Example
5.3.
Java
6.
Using Recursion
6.1.
How It Works
6.2.
Example
6.3.
Java
7.
Using StringBuilder Class
7.1.
How it Works
7.2.
Example
7.3.
Java
8.
8.1.
Can all numbers be reversed using these methods?
8.2.
What happens when reversing a number leads to overflow?
8.3.
Is one method better than the others?
9.
Conclusion
Last Updated: May 21, 2024
Easy

Reverse the Number in Java

Ravi Khorwal
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Reversing a number is a common programming problem that involves turning a given number around so that its digits are in the opposite order. For example, if we have the number 12345, reversing it would give us 54321. This concept is useful in various scenarios, such as checking if a number is a palindrome or performing mathematical operations on reversed numbers.

In this article, we will learn about different methods to reverse a number in Java, including using a while loop, recursion, & the StringBuilder class.

Algorithm for Reversing a Number in Java

To reverse a number in Java, we primarily focus on a logical approach that systematically flips the digits from the end to the start. The basic idea is to isolate each digit of the number and then construct the reversed number by appending each digit from the end to a new number.

Step-by-Step Process

• Initialize Variables: Start by creating a variable to store the reversed number, typically set to 0. You will also need the original number, which should be input or defined beforehand.

• Extract Digits: Using a loop, repeatedly extract the last digit of the current number. This can be done using the modulo operator %. For example, if your number is 123, 123 % 10 gives you 3.

• Build the Reversed Number: Multiply the reversed number by 10 and add the extracted digit to it. This step gradually builds up the reversed number from the rightmost to the leftmost digit.

• Reduce the Original Number: Divide the original number by 10 to remove the digit you just processed. Continue this process until the original number is reduced to 0.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Example

• Java

Java

``public class NumberReverser {    public static int reverseNumber(int number) {        int reversed = 0;        while (number != 0) {            int digit = number % 10;  // Get the last digit            reversed = reversed * 10 + digit;  // Append digit to reversed number            number /= 10;  // Remove the last digit from number        }        return reversed;    }    public static void main(String[] args) {        int originalNumber = 1234;        int reversedNumber = reverseNumber(originalNumber);        System.out.println("Reversed Number: " + reversedNumber);    }}``

Output

``Reversed Number: 4321``

This code utilizes basic arithmetic operations to separate and reassemble the number in reverse order. The loop continues until all digits have been processed and the original number becomes zero.

Methods to Reverse a Number in Java

There are several techniques in Java to reverse a number, each using different logic and Java features. Let's explore the most common methods: using a while loop, using recursion, and using the StringBuilder class.

Using While Loop

The while loop method is very direct and efficient for reversing a number. This method follows the step-by-step algorithm we discussed earlier. It continually extracts the last digit of the number and builds the reversed number until the original number is reduced to zero.

How it Works

• Initialize the Reversed Number: Start with a variable reversed set to zero. This variable will store the final reversed number.

• Loop Until No More Digits: Use a while loop that runs as long as the original number is not zero.

• Extract & Append Digits: Inside the loop, extract the last digit of the number using the modulo operator (%). Add this digit to the reversed number, but first, shift the current digits of reversed to the left by multiplying by 10. This makes space for the new digit.

• Reduce the Number: After extracting the digit, divide the original number by 10 to drop the last digit, effectively shrinking the number.

• Java

Java

``public class ReverseNumberWithLoop {    public static int reverse(int number) {        int reversed = 0;        while (number != 0) {            int lastDigit = number % 10;  // Extract the last digit            reversed = reversed * 10 + lastDigit;  // Append it to the reversed number            number /= 10;  // Drop the last digit from the number        }        return reversed;    }    public static void main(String[] args) {        int original = 4567;        int reversed = reverse(original);        System.out.println("Original: " + original + " - Reversed: " + reversed);    }}``

Output

``Original: 4567 - Reversed: 7654``

This code successfully reverses the number by using basic arithmetic operations without any need for complex structures or external libraries. It's a clear and efficient way to see how numbers can be manipulated using loops in Java.

Using Recursion

Recursion is a programming technique where a method calls itself to solve a problem. In the context of reversing a number in Java, recursion allows us to simplify the process by breaking down the problem into smaller, more manageable tasks.

How It Works

• Base Case: This is crucial in recursion to stop the recursive call. For reversing a number, the base case occurs when the number has no more digits left (i.e., the number is 0).

• Recursive Call: In each recursive step, we split the number into two parts: the last digit and the rest of the number. We then call the method again with the rest of the number, building up the reversed number as we return from each recursive layer.

• Building the Reversed Number: As the recursive calls return, we assemble the reversed number by multiplying the current reversed number by 10 and adding the last digit of the current recursive call's number.

• Java

Java

``public class ReverseNumberRecursively {    public static int reverse(int number, int reversed) {        if (number == 0) {            return reversed;  // Base case: If number is zero, return reversed        } else {            int lastDigit = number % 10;  // Get the last digit            return reverse(number / 10, reversed * 10 + lastDigit);  // Recursive call        }    }   public static void main(String[] args) {        int original = 2345;        int reversed = reverse(original, 0);        System.out.println("Original: " + original + " - Reversed: " + reversed);    }}``

Output

``Original: 2345 - Reversed: 5432``

In this example, reverse is called recursively, decreasing the original number by removing the last digit (by dividing by 10) and building the reversed number by appending this last digit. The process repeats until the original number is reduced to 0, at which point the complete reversed number is returned.

Note -: Recursion provides a clean and logical way to reverse numbers, making it easier to understand how smaller parts of a problem are tackled one step at a time.

Using StringBuilder Class

The StringBuilder class in Java provides a simple and efficient way to manipulate strings. When it comes to reversing a number, we can use this class to handle the number as a string, reverse the string, and then convert it back to a number.

How it Works

1. Convert Number to String: Start by converting the integer number to a string. This allows us to use the string manipulation capabilities of the StringBuilder.

2. Reverse the String: Create a StringBuilder instance with the number string. Use the reverse() method of StringBuilder to reverse the string in place.

3. Convert Back to Integer: Once the string is reversed, convert it back to an integer using Integer.parseInt().

• Java

Java

``public class ReverseNumberWithStringBuilder {    public static int reverse(int number) {        StringBuilder sb = new StringBuilder();        sb.append(number);  // Append the number to StringBuilder        sb.reverse();  // Reverse the string        return Integer.parseInt(sb.toString());  // Convert the reversed string back to an integer    }    public static void main(String[] args) {        int original = 56789;        int reversed = reverse(original);        System.out.println("Original: " + original + " - Reversed: " + reversed);    }}``

Output

``Original: 56789 - Reversed: 98765``

This method is particularly useful for those who prefer working with strings and want a method that is both readable and straightforward. The StringBuilder is efficient and makes the code easy to understand and maintain.

Can all numbers be reversed using these methods?

Yes, all integers, including negative numbers, can be reversed using these methods. For negative numbers, handle the sign separately to maintain its negativity after reversal.

What happens when reversing a number leads to overflow?

If reversing a number results in a value beyond the range of int data type, it will cause an overflow, potentially leading to incorrect results. It's important to check the size of the number before reversing.

Is one method better than the others?

Each method has its merits depending on the situation. Using loops is straightforward and fast, recursion is elegant but could lead to stack overflow with very large numbers, and the StringBuilder method is very readable and easy to implement but less numerical.

Conclusion

In this article, we have talked about the various methods to reverse a number in Java, each offering a unique approach to solving the problem. We started our article with a simple algorithm using a while loop, then we moved on to a more advanced recursive method that elegantly breaks down the problem, and finally, we used the StringBuilder class for those preferring to work with string manipulations.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Live masterclass