Reversing The Digits Of A Number
Another
classic problem asks us to
reverse the digits of a natural number consisting of exactly three digits,
that is, to find its
reverse1.
1 Also known as the inverse or mirror image.
Example:
So, we start with the number
725, stored in the variable
n:
n = 725
LAST DIGIT
Again, we turn to
mathematics, where we already know the
Theorem of Division with Remainder.
If we divide
725 by
10, the remainder will be
5, exactly what we need:
So, we can write as the
first step:
c3 = n % 10
where
c3 is a
temporary variable that will hold the
last digit. The "
%" (
modulo)
operator gives us the remainder of the division by
10.
SECOND LAST DIGIT
First, we need
72, which is the quotient of
725 divided by
10:
which we will use to find the remainder when divided by
10, which is
2:
So, we will define another intermediate variable,
c2, which will hold the expression:
c2 = (n // 10) % 10
Read: the quotient of
n divided by
10, all
modulo 10.
The "
//" operator represents integer division (quotient), already studied.
FIRST DIGIT
Using the "
//" operator again, we can immediately find the first digit:
So, in the program, we will write:
c1 = n // 100
where the variable
c1 will hold the first digit, which is
7.
Read: the quotient of
n divided by
100 ...
CREATING THE REVERSE
We use multiplication and addition:
because
c1 holds the hundreds,
c2 the tens, and
c3 the units:
invers = c3*100 + c2*10 + c1
Finally, we display the value of the variable
invers.
THE PROGRAM IN PYTHON
Remember that a
solid mathematical/analytical thinking is essential:
HOW DID WE THINK OF THE ALGORITHM?
First, we determined that we needed to
access the digits, meaning we needed to identify each one.
Then, we used these digits to create a new number that holds them in reverse order.
Therefore,
we divided the problem into smaller subproblems and solved each one. Each step corresponds to an instruction above.
PROPOSED EXERCISES
Modify the algorithm to reverse a number consisting of two digits.
Can you do it for four digits?
Run the program and read the information.