The following program demonstrates how to Find the Reverse of a Number in Java.
While the logic for determining the reverse of a number is similar to the previous program that finds the sum of digits of the number.
https://www.programmingempire.com/display-the-sum-of-digits-of-a-number-in-java/
After retrieving the last digit of the number as the remainder, we find the sum as follows.
sum=sum+remainder X 10^current-length
For example,
let number = 3456, len=4, i=len-1=3
(I) remainder=6, sum=6 X (10^3)=6000, n=345, i=3-2=1
(ii) remainder=5, sum=6000+5 X (10^2)=6500, n=34, i=2-1=1
(iii) remainder=4, sum=6500+4 X (10^1)=6540, n=3, i=1-1=0
(iv) remainder=3, sum=6540+3 X (10^0)=6543, n=0
The loop terminates and we get the reverse of the number.
import java.util.Scanner;
import java.lang.Math;
public class Exercise16
{
public static void main(String[] args) {
int num, n, i, sum, len, rem;
System.out.println("Enter a Number: ");
num=(new Scanner(System.in)).nextInt();
len=0;
n=num;
while(n>0)
{
n=n/10;
len++;
}
sum=0;
i=len-1;
n=num;
while(n>0)
{
rem=n%10;
sum=sum+rem*(int)(Math.pow(10, i));
n=n/10;
i=i-1;
}
System.out.println("Original Number: "+num+"\nReversed Number: "+sum);
}
}
Output