Your Page Title
🔍

    How to reverse a number in Python

    There are several ways to reverse a number in Python. Here is a detailed explanation using three common approaches: converting to a string, mathematical operations, and using recursion.

    1. Using String Conversion

    The simplest way to reverse a number is by converting it to a string, reversing the string, and then converting it back to a number.

    Code Example:

    # Input number
    num = 12345
    
    # Convert to string, reverse, and convert back to integer
    reversed_num = int(str(num)[::-1])
    
    print("Reversed Number:", reversed_num)

    Explanation

    1. str(num): Converts the number to a string ("12345").
    2. [::-1]: Slices the string in reverse order ("54321").
    3. int(): Converts the reversed string back to an integer (54321).

    2. Using Mathematical Operations

    This approach uses arithmetic to reverse the number without converting it to a string.

    Code Example:

    # Input number
    num = 12345
    reversed_num = 0
    
    # Loop until the number becomes 0
    while num > 0:
        digit = num % 10         # Extract the last digit
        reversed_num = reversed_num * 10 + digit  # Append the digit to the reversed number
        num = num // 10          # Remove the last digit from the original number
    
    print("Reversed Number:", reversed_num)

    Explanation:

    1. num % 10: Extracts the last digit of the number.
    2. reversed_num * 10 + digit: Left shifts the digits of reversed_num and adds a new digit at the right.
    3. num // 10: Removes the least-significant digit from num.

    3. Using Recursion

    This method involves a recursive function to reverse the number.

    Code Example:

    def reverse_number(num, rev=0):
        if num == 0:
            return rev
        else:
            digit = num % 10
            return reverse_number(num // 10, rev * 10 + digit)
    
    # Input number
    num = 12345
    reversed_num = reverse_number(num)
    
    print("Reversed Number:", reversed_num)

    Explanation:

    1. The base case is when num becomes 0, at which point the reversed number (rev) is returned.
    2. At each recursive step:
      • Get the last digit by using num % 10.
      • Append the digit to rev by multiplying rev by 10 then adding the digit.
      • Remove the last digit from num by doing num // 10.

    Choosing the Right Method

    1. String Conversion: Simple and rapid for most application scenarios.
    2. Mathematical Operations: Good for problems where you can’t manipulate strings.
    3. Recursion: Good for understanding recursion or solving problems programmatically.