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 2 3 |
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.
1 2 3 |
i.e. 1532 mod 10 = 2 |
To get the remaining number 153, Use integer division by 10 with
the number.
1 2 3 |
i.e, int(1532 div 10) = 153 |
To generalize above steps, imagine n is the number to be reverse
then,
1 2 3 4 5 |
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).
1 2 3 |
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.
1 2 3 4 |
23 * 10 + 5 = 235 235 * 10 + 1 = 2351 |
We are done!
To generalize above steps, initialize a variable reverse with zero.
1 2 3 |
i.e,reverse = reverse * 10 + r |
implement in C:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include<stdio.h> main() { int reverse = 0; int r,n; printf("Enter the number to reverse"); scanf(%d,&n); while(n>0){ r = n mod 10; n = n / 10; reverse = (reverse *10) + r; } printf(The reversed number is :%d,reverse); return 0; } |