Reversing a Number in Python: Step-by-Step with Modulo Logic

Reversing a Number in Python

This program takes an integer and reverses the order of its digits. Instead of cheating by converting the number to a string, it uses pure arithmetic. By repeatedly extracting the last digit using the modulo operator (%) and shifting the existing digits using integer division (//), we can reconstruct the number in reverse.


The Python Code

# This program reverses a given integer using arithmetic (divide by 10 and remainder logic).

def reverse_number(number):
    # Initialize a variable to hold the reversed number, starting at 0
    reversed_num = 0
    
    # Keep track of whether the original number was negative
    is_negative = number < 0
    
    # Convert to positive to safely handle the math logic
    number = abs(number)
    
    # Loop until all digits are extracted and the number becomes 0
    while number > 0:
        # Get the last digit of the number using the remainder when divided by 10
        remainder = number % 10
        
        # Shift the existing reversed digits left by multiplying by 10, then add the new remainder
        reversed_num = (reversed_num * 10) + remainder
        
        # Remove the last digit from the original number using integer division
        number = number // 10
        
    # If the original number was negative, turn the reversed result back to negative
    return -reversed_num if is_negative else reversed_num

# Example usage:
num_to_reverse = 12345
result = reverse_number(num_to_reverse)
print("Reversed number:", result)

Sample Inputs & Outputs

Here is how the algorithm processes different types of integers, including edge cases like negative numbers and trailing zeros.

Input Type Input Output
Standard Positive 12345 54321
Negative Integer -9876 -6789
Trailing Zeros 1200 21 (Leading zeros are dropped natively)
Single Digit 7 7

Comments