YouTip LogoYouTip

Python Reverse Number

## Python Program to Reverse a Number Reversing a number is a classic programming problem often used to teach basic arithmetic operations, loops, and string manipulation. In Python, there are multiple ways to achieve this, ranging from mathematical approaches to elegant string slicing techniques. In this tutorial, we will explore the most common and efficient methods to reverse an integer in Python, complete with code examples, detailed explanations, and edge-case considerations. --- ## Method 1: Using Mathematical Operations (Arithmetic Approach) This method uses basic arithmetic operationsβ€”modulo (`%`) and integer division (`//`)β€”inside a `while` loop. It is highly efficient because it works directly with the numeric values without converting them to strings. ### Code Example ```python def reverse_number(n): reversed_num = 0 while n > 0: # Get the last digit of the number digit = n % 10 # Append the digit to the reversed number reversed_num = reversed_num * 10 + digit # Remove the last digit from the original number n = n // 10 return reversed_num # Test the function number = 12345 print("Reversed number is:", reverse_number(number)) ``` ### Output ```text Reversed number is: 54321 ``` ### Code Explanation 1. **Function Definition**: The `reverse_number` function accepts an integer `n` as its parameter. 2. **Initialization**: `reversed_num` is initialized to `0`. This variable will store the final reversed integer. 3. **Loop Condition**: The `while` loop runs as long as `n` is greater than `0`. 4. **Extracting the Last Digit**: `digit = n % 10` uses the modulo operator to extract the last digit of `n` (e.g., `123 % 10` results in `3`). 5. **Building the Reversed Number**: `reversed_num = reversed_num * 10 + digit` shifts the existing digits of `reversed_num` one place to the left and adds the newly extracted digit to the end. 6. **Updating the Original Number**: `n = n // 10` performs integer division to discard the last digit of `n` (e.g., `123 // 10` results in `12`). 7. **Return Value**: Once `n` becomes `0`, the loop terminates, and the function returns `reversed_num`. --- ## Method 2: Using String Slicing (The Pythonic Way) Python provides a highly concise and readable way to reverse sequences (like strings and lists) using slicing syntax: `[:: -1]`. We can convert the integer to a string, reverse it, and then convert it back to an integer. ### Code Example ```python def reverse_number_string(n): # Convert the number to a string, reverse it, and convert it back to an integer reversed_num = int(str(n)[::-1]) return reversed_num # Test the function number = 98765 print("Reversed number is:", reverse_number_string(number)) ``` ### Output ```text Reversed number is: 56789 ``` ### Code Explanation * `str(n)` converts the integer `n` into its string representation (e.g., `98765` becomes `"98765"`). * `[::-1]` slices the string from end to start with a step of `-1`, effectively reversing it (e.g., `"98765"` becomes `"56789"`). * `int(...)` casts the reversed string back into an integer. --- ## Handling Edge Cases When writing production-ready code, you must consider edge cases such as **negative numbers** and **trailing zeros**. ### 1. Handling Negative Numbers The basic mathematical and string slicing methods shown above do not natively handle negative signs. Here is how to handle negative integers properly: ```python def reverse_any_integer(n): # Determine the sign of the number sign = -1 if n < 0 else 1 # Work with the absolute value n = abs(n) # Reverse using string slicing reversed_num = int(str(n)[::-1]) # Restore the original sign return sign * reversed_num # Test cases print("Reversed -123:", reverse_any_integer(-123)) print("Reversed 1200:", reverse_any_integer(1200)) ``` ### Output ```text Reversed -123: -321 Reversed 1200: 21 ``` ### 2. Handling Trailing Zeros If a number ends with one or more zeros (e.g., `1200`), reversing it mathematically or converting it back to an integer will naturally drop the leading zeros in the result (e.g., `1200` reversed becomes `21`). This is mathematically correct. If your application requires preserving the leading zeros in the output (e.g., outputting `"0021"`), you should keep the reversed result as a **string** instead of converting it back to an integer. --- ## Summary of Methods | Method | Complexity | Pros | Cons | | :--- | :--- | :--- | :--- | | **Mathematical (`while` loop)** | Time: $O(\log_{10} N)$
Space: $O(1)$ | Memory efficient; does not require type conversion. | Requires more lines of code; does not handle negative numbers out of the box. | | **String Slicing (`[::-1]`)** | Time: $O(\log_{10} N)$
Space: $O(\log_{10} N)$ | Extremely concise and readable (Pythonic). | Requires type conversion overhead; requires manual sign handling for negative numbers. |
← Python Recursive FactorialPython While Loop2 β†’