Algorithm to reverse order of digits of an integer.

In this guide, we going to learn a programming algorithm to reverse the order of digits of an integer. Here explains the algorithm to Reverse the order of digits of a positive integer.

 

Development:

A specific example of reversing is,
Input no: 1532
Reversed output: 2351Actually, the number 1532 is

Actually, the number 1532 is

1*(10^3)+5*(10^2)+3*(10^1)+2*(10^0)

 

We can access each digit. and start the access from rightmost (least significant digit). To chop off a least significant digit from the number, use mod 10, mod give a reminder of the division.

i.e. 1532 mod 10 = 2

 

To get the remaining number 153, Use integer division by 10 with
the number.

i.e, int(1532 div 10) = 153
 Repeat the above two steps to access each digit in the number.


To generalize above steps, imagine n is the number to be reverse
then,

n mod 10 = r;
  r is the least significant digit
  n = int(n / 10);

 

The next step is to reverse the number, In above example 2 is the first digit and 3 is second.We can reverse it by 2 (least significant digit)is multiplying with 10 and add it with 3 (next significant digit).

i.e, 2*10 + 3 = 23

 

Repeat the above steps until fully reverse the number.
Use while loop with condition n>0 to repeat the steps.

23 * 10 + 5 = 235
235 * 10 + 1 = 2351

 

We are done!

To generalize above steps, initialize a variable reverse with zero.

i.e,reverse = reverse * 10 + r

 

Reverse order

 

implement in C:

#include<stdio.h>
main()
{
&nbsp;&nbsp;&nbsp; int reverse = 0;
&nbsp;&nbsp;&nbsp; int r,n;
&nbsp;&nbsp;&nbsp; printf("Enter the number to reverse");
&nbsp;&nbsp;&nbsp; scanf(%d,&n);
&nbsp;&nbsp;&nbsp; while(n>0){
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; r = n mod 10;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; n = n / 10;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; reverse = (reverse *10) + r;
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp; printf(The reversed number is :%d,reverse);
&nbsp;&nbsp;&nbsp; return 0;
}

Anwar Yakkiparamban

Anwar Yakkiparamban is the founder of Lauyou Learning. Prior to Lauyou learning, Anwar worked at ARD Engineering & Development, Qatar. He holds bachelor degree in Electronics and Communication Engineering from Govt. Engineering College Idukki.

You may also like...