Java Program to Reverse a Number

In this post, we will know how to reverse a number Using Java Programming language. Let’s see the Java Program to reverse a number.

Java program to reverse a number

Reverse a number means interchanging the digit of the number like 1st digit is swapped with the last digit, 2nd digit is swapped with second last digit and so on.

For example, if the number given is 12345, then after reverse, it will become 54321.

Now, let’s straight get into the code of Java Program to reverse a number.

Java Program To Reverse a Number

import java.util.*;
   
   public class Main{
   
   public static void main(String[] args) {
     Scanner sc = new Scanner(System.in);
     int num = sc.nextInt();
     
     int originalNumber = num;
     int reversedNumber = 0;
     
     while(num > 0){
         int digit = num % 10;
         num = num / 10;
         reversedNumber = reversedNumber * 10 + digit; 
     }
     
     System.out.println("Original Number : "+originalNumber);
     System.out.println("Reversed Number : "+reversedNumber);
    }
   }

Output

Original Number : 12345
Reversed Number : 54321

How Does This Program Work ?

In this program, we have taken the Input of the number we want to reverse using the Scanner Class in Java. Then we have just preserved the original number as we are going to perform the operation on the number and hence the original number will be lost.

Scanner sc = new Scanner(System.in);
     int num = sc.nextInt();
     
     int originalNumber = num;

If you want to learn more about taking inputs in Java, read this : Input in Java

Now, lets understand the logic to reverse the number in Java.

while(num > 0){
         int digit = num % 10;
         num = num / 10;
         reversedNumber = reversedNumber * 10 + digit; 
     }
java reverse number logic 1

So, we are dividing the num till it becomes 0, and using the remainder we can form the Reversed Number.

remainder = remainder * 10 + digit

By using the equation we will form the reversed number. It will be more clear with an example and dry run. so let’s see :

java reverse number logic 2
System.out.println("Original Number : "+originalNumber);
System.out.println("Reversed Number : "+reversedNumber);

So, we have just reversed our given number. Now just print both the number.

Conclusion

I hope after going through this post, you understand how to reverse a number in Java Programming language and learned to code a Java Program to Reverse a Number.

If you have any doubt regarding the topic, feel free to contact us in the comment section. We will be delighted to help you.

Also Read:

Leave a Comment

Your email address will not be published. Required fields are marked *