Reversing an integer
Printing a positive integer in reverse form. for e.g. printing 123 as 321.
Learning Objectives
- Concept of number reversal by individual digit handling.
- Concept of shifting individual digit within a number to the left side.
Program Approach
- A copy of number is first saved in a different number which can then be operated upon.
- Reversal is done by extracting individual digits from the last digit using the % or mode operator which gives the remainder of division operation.
Source Code
Run Output
Code Understanding
int nc=n;
Here we are simply storing n into its copy nc so that processing can be done on nc without disturbing the original number n. Let us try with a test case 123. nc will also contain 123
while(nc>0) {
In this loop we will extract each digit from the last number and then store it in nr the number where reversed number is prepared.
rem=nc%10;
Here we are extracting the last digit by % (mod) operator as remainder of the division. after first traversal rem will be 3 then 2 and then 1.
nr=nr*10+rem;
Here we are shifting the previously extracted digit to left so that reversal process can begin. Left traversal of digit is by multiplying it with 10 and then adding the new last extracted digit. After first traversal nr will be 3 then 32 and then 321.
nc=nc/10;
Here the extracted last digit is being dropped, so that individual digit can be operated upon. After first traversal nc will be 12 (3 dropped), then 1 (2 dropped) and then 0 (1 dropped)
Finally nr will contain 321 as it comes out of loop, which is reversed number of 123.
Notes
Negative integer inputs will yield 0 after reversal with this method,
Suggested Filename(s): revnum.cpp, numreverse.cpp
Created: 2-Dec-2017 18:23 | Updated: 15-Sep-2018 13:50|
