Reverse a Number Using Recursion and use of Global Variable

In this class, we write a program to Reverse Number Using Recursion and use of Global Variable.

For Complete YouTube Video: Click Here

Reverse a number using recursion

The reader should have prior knowledge of our previous examples. Click here.

We use the logic from our previous examples.

Take an example and understand the logic to reverse a number using recursion.

Example

a=12567

a//10 if we do floor division, the result is 1256. we are eliminating the last digit.

a%10 if we do modulus with 10. we get the output 7. The first digit is taken out.

We use the concepts mentioned above to write the code.

Input: a= 12567

Output = 76521

Initially, take a variable digit = 0.

Logic

12567//10 will result in 1256.

1256//10 will result in 125

125//10 will result in 12

12//10 will result in 1

Logic is to divide the number till the number has one digit.

Now after dividing the number up to one digit. We remain with the last digit in the number.

 This last digit should be the first digit in our output.

The last digit in the input will be in one’s position in the output.

The last digit is multiplied by 1 to place it in one’s position.

The same way last before digit is multiplied by 10 to place it in the tens position.

Continue with this logic. The logic is shown below.

Initially digit = 0

digit = (last digit * 1 + digit) =1

digit = (last before digit * 10 + digit) = 21

digit = (third digit from last *100 + digit) = 521

repeat the logic till the first digit in the input is considered.

Use of Global Variable

To implement the above logic, we are using recursion.

Each time we are calling the function recursively until a single digit remains.

The remainder value is multiplied by position and added with digit value.

The digit and position variable are used in every function. We have to declare those variables global.

Because local variables are lost after completion of the function.

Analyze the below program for better practice.

Program

digit=0
tenpower=1
number=int(input("enter number"))
def rever(number):
    global tenpower
    global digit
    if(number>10):
        rever(number//10)
    digit=(number%10)*tenpower+digit
    tenpower=tenpower*10
rever(number)
print(digit)