Program to reverse digits in a number

Simple java program to reverse the digits in a number. Logic for reversing the number, sum of digits and armstrong number are similar, even in c sharp, php, c++, c.  To reverse, digits are manipulated from last position. Solution and explanation, for the program is below.

 

class RevNumber
{
public static void main(String args[])
{
int s=0,x,n=425;
while(n > 0)
{
x=n%10;
s=s*10+x;
n=n/10;
}
System.out.println(“ The Reversed number is :”+ s);
}
}

 

Result displayed by the above program:

The Reversed number is : 524

 

Solution with Explanation for the code:

n=425

1 st iteration

line 8: x=5

line 9: s=0*10+5 =5

line 10: n=42

 

2 nd iteration, now n=42

 

line 8: x=2

line 9: s=5*10+2 =52

line 10: n=4

3 rd iteration, now n=4

line 8: x=4

line 9: s=52*10+4=524

line 10: n=0