Java Program to Reverse a Number

Here you will get java program to reverse a number with while loop and recursion.

When we divide a number with 10 then the remainder is the last digit of number and quotient is the number without last digit. / operator is used find quotient and % operator is used to find remainder. We use this concept to reverse the number.

Example:

Initially n = 123, reverse = 0

Step 1:

remainder = n % 10 = 123 % 10 = 3

reverse = (reverse * 10) + remainder = (0 * 10) + 3 = 3

n = n / 10 = 123 / 10 = 12

Step 2:

remainder = n % 10 = 12 % 10 = 2

reverse = (reverse * 10) + remainder = (3 * 10) + 2 = 32

n = n / 10 = 12 / 10 = 1

Step 3:

remainder = n % 10 = 1 % 10 = 1

reverse = (reverse * 10) + remainder = (32 * 10) + 1 = 321

n = n / 10 = 1 / 10 = 0

We repeat above steps until n becomes 0. Finally reverse of number is obtained.

Java Program to Reverse a Number

Using While Loop

 

Output

Enter a number:
1159
Reverse of number is 9511

 

Using Recursion

 

Output

Enter a number:
8764
Reverse of number is 4678

 

Comment below if you have doubts or found anything incorrect in above java program to reverse a number.

 

Leave a Reply

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