1. Introduction

Reversing a number is a common task in programming challenges and can be used to solve various problems, such as checking for palindromes. In this post, we’ll see how to reverse an integer in Python.

To reverse an integer, we take its digits from the end and reconstruct a new number by placing the digits from the least significant position to the most significant position in the original number.

2. Program Steps

1. Define a recursive function that reverses an integer.

2. Identify the base case for the recursion to stop.

3. Extract the last digit of the number and incrementally build the reverse number.

4. Reduce the original number by removing the last digit.

5. Return the reversed number once all digits have been processed.

3. Code Program

def reverse_number(n, reverse=0):
    # Base case: if the original number is 0, the reversed number is fully constructed
    if n == 0:
        return reverse
    else:
        # Step 1: Extract the last digit of the number
        last_digit = n % 10
        # Step 2: Add it to the reversed number at the correct place value
        reverse = (reverse * 10) + last_digit
        # Step 3: Remove the last digit from the original number and recurse
        return reverse_number(n // 10, reverse)

Output:

print(reverse_number(12345))  # Output: 54321
print(reverse_number(1000))   # Output: 1
print(reverse_number(-123))   # Output: -321

Explanation:

1. A recursive function reverse_number is defined with n as the number to reverse and reverse as the accumulator for the reversed number.

2. The base case occurs when n is 0. At this point, the function returns the reverse number.

3. If n is not 0, the last digit is obtained using n % 10.

4. This last digit is added to the reverse number after multiplying the current reverse by 10, which shifts the digits left, making room for the new digit.

5. The original number n is truncated by removing the last digit using integer division by 10.

6. The function is called recursively with the updated n and reverse until n becomes 0.

7. The output correctly shows the reversed numbers for both positive and negative integers, as well as accounts for trailing zeros.