This article discussed several ways to reverse an integer number in Python. It is helpful to check if the number is a palindrome.
Let’s discuss each of them in detail with examples using Python.
Table of contents
1. How to reverse an integer number in Python
Below are the steps to reverse an integer number using string slicing in Python.
- Get Input
Accept an integer number from a user using the
input()function. - Conversion
Converts the integer number into a string using
str()function . For Example,str(1234) = "1234" - Reverse the String Using Slicing
The slicing syntax
[::-1]is a powerful way to reverse a string in Python. For Example,"1234"[::-1] = "4321" - Handle Negative Numbers
Here, we remove the last character of the reversed string, which is the ‘-‘ sign, and place it in front of the reversed string.
For Example,n = -5678.reversed_str= "8765-"
res ='-' + reversed_str[:-1]= it removes the last character ('-') and ensures the'-'is placed at the front - Convert Back to Integer
Converts the reversed string back to an integer using
int()function. For Example,int("4321") = 4321
Code Example
Output:
Reversed Integer: 654321Code language: Python (python)
2. Using a Mathematical Approach
The mathematical approach to reversing an integer involves extracting each digit from the number and building a new reversed number. This method does not rely on converting the number into a string but instead uses modulus (%) and division (//) operations.
Understanding how digits are extracted:
Consider a number 1234. To extract the last digit, we use:
- Modulus operator (
% 10):1234 % 10 = 4(Extract the last digit) - Floor division (
// 10):1234 // 10 = 123(Remove the last digit)
Using this approach, we can extract each digit one by one.
Constructing the reversed number:
We initialize a variable reversed_num = 0. To build the reversed number, we follow this pattern:
- Multiply
reversed_numby10to shift digits to the left. - Add the extracted digit.
Handling Negative Numbers: If the number is negative, we can:
- Reverse it using the same logic.
- Restore the negative sign at the end.
For example, let’s reverse 1234:
| Step | Original Number n | Extracted Digit (n % 10) | reversed_num =(reversed_num * 10 + digit) |
|---|---|---|---|
| 1 | 1234 | 4 | 0 * 10 + 4 = 4 |
| 2 | 123 | 3 | 4 * 10 + 3 = 43 |
| 3 | 12 | 2 | 43 * 10 + 2 = 432 |
| 4 | 1 | 1 | 432 * 10 + 1 = 4321 |
| 5 | 0 (Done) | – | Final reversed number: 4321 |
Code Example
3. Using Recursion
Recursion is a method where a function calls itself to break down a problem into smaller subproblems. To reverse an integer recursively, we use the same mathematical formula discussed in the above approach, where we extract digits one by one and construct the reversed number in each recursive call.
Understanding the Recursive Approach:
To reverse a number n, we need to:
- Extract the last digit (
n % 10). - Reduce the number (
n // 10). - Accumulate the extracted digits in reverse order.
For example, reversing 1234 using recursion follows this pattern:
| Step | Current n | Extracted Digit (n % 10) | Remaining Number (n // 10) | Partial Result |
|---|---|---|---|---|
| 1 | 1234 | 4 | 123 | 4 |
| 2 | 123 | 3 | 12 | 43 |
| 3 | 12 | 2 | 1 | 432 |
| 4 | 1 | 1 | 0 (Base Case) | 4321 |
The recursion stops when n == 0 (base case).
Code Example
4. Using List Reversal
A list reversal approach involves converting the integer into a list of its digits, reversing the order of the list, and then converting it back to an integer. This method utilizes Python’s built-in list manipulation capabilities, such as list() and reverse(), to efficiently reverse the digits.
Explanation
- Handle negative number: check if num is negative:
- If num < 0, sign = -1 (negative number).
- Otherwise, sign = 1 (positive number).
- Since num = 123456 (positive), sign = 1.
- Convert the Number to a List of Characters:
str(num)converts 123456 into the string ‘123456’.list(str(num))converts ‘123456’ into a list:digits = ['1', '2', '3', '4', '5', '6']
- Reverse the List:
- The
reverse()method reverses the list in place, modifyingdigits = ['6', '5', '4', '3', '2', '1']
- The
- Convert the Reversed List Back to an Integer:
''.join(digits)joins the list back into a string: ‘654321’int('654321')converts the string back to an integer: 654321
- Adjust the sign: Multiply by
sign: reverse_int = 1 * 654321. Since sign = 1
Summary
Each of these methods can reverse an integer in Python. The choice of method may depend on your specific needs, such as readability, performance, etc.
- Using String Slicing (
[::-1])- Advantage: Simple and concise.
- Time Complexity:
O(d), wheredis the number of digits. - Space Complexity:
O(d), since a new string is created, where d = number of digits
- Using a Mathematical Approach
- Advantage: Most efficient approach. No string conversion, reducing memory usage.
- Time Complexity:
O(log n), since each loop iteration removes one digit. - Space Complexity:
O(1), as no extra storage is needed.
- Using List Reversal
- Advantage: Uses Python’s built-in list operations. Easy to understand.
- Time Complexity:
O(d), due to list reversal. - Space Complexity:
O(d), since the list stores digits.
- Using Recursion
- Advantage: A structured and elegant solution.
- Time Complexity:
O(log n), since each recursive call removes one digit. - Space Complexity:
O(log n), due to the recursive call stack.

Leave a Reply