How to Find Reverse of a Number in Java

How to Find Reverse of a Number in Java

4 mins read4.6K Views Comment
Atul
Atul Harsha
Senior Manager Content
Updated on Jan 10, 2023 16:55 IST

Reversing a number in Java is a common task that can be accomplished using a variety of methods. For example, you can use a loop to iterate over the digits of the number and build the reversed number one digit at a time. Alternatively, you can convert the number to a string, reverse the string using the built-in StringBuilder class, and then parse the reversed string back into a number. Other options include using a character array or recursion to reverse the number. When deciding on the best method, consider factors such as time complexity, space complexity, and code simplicity.

2022_02_j.jpg

In this blog we will learn 5 different ways in which you can write a function to find the reverse of a number in Java.

Problem: Write a Java program that reads an integer from the user and prints the reverse of the integer. The program should continue to prompt the user for integers until the user enters 0.

Example:

Enter a number: 12345
The reverse of 12345 is 54321
Enter a number: 123
The reverse of 123 is 321
Enter a number: 0
Cannot reverse a single digit number

Explore other popular Java Courses

Method 1: Reverse a Number in Java Using a Loop

  • Initialize a variable reverse to 0.
  • While num is not 0:
    • Append the last digit of num to reverse by performing the following steps:
    • Multiply reverse by 10.
    • Add the last digit of num to reverse.
    • Remove the last digit of num by dividing num by 10.
  • Return reverse.
 
public static int reverse(int num) {
int reverse = 0;
while (num != 0) {
reverse = reverse * 10 + num % 10;
num /= 10;
}
return reverse;
}
Copy code

Dry Run Explanation:

Let’s say we want to reverse the number 12345. Here is how the method would work:

Iteration reverse num num % 10 New value of reverse New value of num
1 0 12345 5 5 1234
2 5 1234 4 54 123
3 54 123 3 543 12
4 543 12 2 5432 1
5 5432 1 1 54321 0

Read more: Reverse a String in Java

Armstrong Number in Java using Different Methods
Armstrong Number in Java using Different Methods
Learn to check if a number is an Armstrong number in Java using while loop or recursion. Understand the mathematical definition and see code examples for easy implementation
Check Palindrome in Java Using Different Methods
Check Palindrome in Java Using Different Methods
Discover various methods for checking if a string is a palindrome in Java. Use recursion and string manipulation to efficiently determine if a string is a palindrome, ignoring spaces, punctuation,...read more
Fibonacci Series in Java [Case-Study Based]
Fibonacci Series in Java [Case-Study Based]
The Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. In Java, the Fibonacci...read more
Recommended online courses

Best-suited Java courses for you

Learn Java with these high-rated online courses

– / –
350 hours
Free
6 months
– / –
4 months
– / –
– / –
– / –
1 month
40 K
7 weeks
7.8 K
3 months
8.47 K
2 months
7 K
6 months
4 K
2 months

Method 2: Reverse a Number in Java Using a String

  • Convert num to a string.
  • Initialize a variable reverse to an empty string.
  • Iterate through the characters of the string in reverse order:
    • Append each character to reverse.
  • Convert reverse back to an integer and return it.
 
public static int reverse(int num) {
String str = Integer.toString(num);
String reverse = "";
for (int i = str.length() - 1; i >= 0; i--) {
reverse += str.charAt(i);
}
return Integer.parseInt(reverse);
}
Copy code

Dry Run Explanation:

Let’s say we want to reverse the number 12345. Here is how the method would work:

Iteration i str.charAt(i) reverse New value of reverse
1 4 5 “” “5”
2 3 4 “5” “54”
3 2 3 “54” “543”
4 1 2 “543” “5432”
5 0 1 “5432” “54321”
Swapping of Two Numbers in Java
Swapping of Two Numbers in Java
Get an introduction to swapping the values of two numbers in Java using different methods. Compare the use of a temporary variable, arithmetic operators, and bitwise operators for swapping numbers....read more
How to Check Leap Year in Java?
How to Check Leap Year in Java?
In this blog, you will learn how to check leap year in Java. A leap year is a year that is divisible by 4 and 400 but not by 100....read more
Switch Case in Java with Examples
Switch Case in Java with Examples
Switch statements in Java enable execution of different code blocks based on the value of an expression. They provide an alternative to multiple if-else statements and can be used when...read more

Method 3: Reverse a Number in Java Using an Array

  • Convert num to a string and then to an array of characters.
  • Initialize an array reverse of the same size as the original array.
  • Iterate through the original array in reverse order:
  • Set the corresponding element of reverse to the current element of the original array.
  • Convert reverse back to a string and then to an integer and return it.
 
public static int reverse(int num) {
char[] arr = Integer.toString(num).toCharArray();
char[] reverse = new char[arr.length];
for (int i = 0; i < arr.length; i++) {
reverse[i] = arr[arr.length - i - 1];
}
return Integer.parseInt(new String(reverse));
}
Copy code

Dry Run Explanation:

Let’s say we want to reverse the number 12345. Here is how the method would work:

Iteration i arr[arr.length – i – 1] reverse[i] New value of reverse[i]
1 0 5 5
2 1 4 4
3 2 3 3
4 3 2 2
5 4 1 1

In the last line of code, the reverse char array is being converted back to a string using the new String(reverse) constructor. This creates a new string object that contains the same sequence of characters as the reverse array.

Then, the Integer.parseInt() method is being called on the string to parse it as an integer. This returns an int value that is the integer representation of the string. Finally, this int value is returned as the output of the reverse() method.

Method 4: Reverse a Number in Java Using Recursion

  • If num is less than 10, return num.
  • Otherwise, return the last digit of num concatenated with a recursive call to reverse the rest of num.
 
public static int reverse(int num) {
if (num < 10) {
return num;
}
return Integer.parseInt(num % 10 + "" + reverse(num / 10));
}
Copy code

Dry Run Explanation:

Let’s say we want to reverse the number 12345. Here is how the method would work:

Iteration num num % 10 reverse(num / 10) New value of reverse
1 12345 5 1234 5
2 1234 4 123 54
3 123 3 12 543
4 12 2 1 5432
5 1 1 54321

Time and Space Complexity Comparison

Method Time complexity Space complexity
1. Using a loop O(n) O(1)
2. Using a string O(n) O(n)
3. Using a character array O(n) O(n)
4. Using recursion O(log n) O(log n)

In terms of time complexity, the fourth method (using recursion) has the lowest time complexity, followed by the first method (using a loop). The second and third methods (using a string and a character array, respectively) have the same time complexity.

In terms of space complexity, the first method (using a loop) has the lowest space complexity, followed by the second and third methods (using a string and a character array, respectively). The fourth method (using recursion) has the highest space complexity.

About the Author
author-image
Atul Harsha
Senior Manager Content

Experienced AI and Machine Learning content creator with a passion for using data to solve real-world challenges. I specialize in Python, SQL, NLP, and Data Visualization. My goal is to make data science engaging an... Read Full Bio