Reverse of a number - LISP(Scheme)
Reverse of a given number involves 2 main task ,
- Finding what the last digit is
- Finding the remains number aside from last digit
If we solve these tasks then we can easily find the reverse of a given number by simply recursively finding the last digit and trimming the original number.
Aside from this , there is one other problem which we might face which is : the problem of storing the last digit obtained... We can solve that by the following method:
- Intitalize a variable temp which will hold the reversed number with 0.
- perform temp = (temp * 10 ) + last digit.
we initialise temp = 0 only once whereas 2nd step is done at every step, in second step we are actually creating a space for last digit by multiplying it with 10, after which we can simply add the last digit to it.
Now the code for finding out reverse of a given number can be written as :
Now, we basically solve the first problem of finding last digit by using modulo operator...
i.e (modulo number 10) , we solve the second problem by finding the quotient of the number, So our code turns out as keep finding the reverse until the original number becomes 0 , and when that happens return the reversed number.
Written By,
Sarvesh Bhatnagar
No comments:
Post a Comment