I will assume that you know both the given number x and the number of digits in x, n.
integer function Reverse(integer x, y)
{
y= 0; //comment: we will add parts of the answer to y
for i=1 to n
{
k= x/10^{n-i};
//comment: this is computer "integer" arithmetic : 3/2= 1, not 1.5
//comment: mathematically, k= (x- (x mod 10^{n-i}))/10^{n-i}
//comment: if x= 251, for example, n= 3, i=1, 10^{n-1}= 10^2= 100
//comment: then k= 251/100= 2 or k= (251- (251 mod 100))/100= (251- 51)/100= 2
y=y+ k*10^{i-1}
x= x- k;
}
return y;
}
With x= 251, n= 1, the first time through the loop, i= 1, k= 251/10^(3-1)= 251/100= 2 so y= 0+ 2*10^0= 2, x= 251- 200. The second time through the loop, i= 2, x= 51 now, k= 51/10^(3-2)= 51/10= 5 so y= 2+ 5*10= 52, x= 51-50. The third and last time through the loop, i= 3, x= 1, k= 1/10^(3-3)= 1/1= 1 and y= 52+ 1*100= 152, 251 reversed.
If you are given only x, not the number of digits in x, then you can find it this way.
n= 0;
k= 1;
while x>= k do
{
n= n+1
k= k*10
}
For example, if x= 251 again, we first see that 251> 1 so n= 0+ 1= 1. k= 1*10= 10. Since 251> 10, n= 1+1= 2, k= 10*10= 100. Since 251> 100, n= 2+ 1= 3, k= 10*100= 1000. Since 251< 1000, the loop terminates with n= 3, the number of digits in 251.