Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to reverse a number in Python?
Reversing an integer number is a common programming task. You may need to reverse a number for palindrome checking, mathematical operations, or data processing scenarios.
Input: 12345 Output: 54321
There are two main approaches to reverse a number in Python:
Convert the number into a string, reverse the string and reconvert it into an integer
Reverse mathematically without converting into a string
Using String Slicing
This method converts the number to a string, reverses it using Python's slice notation [::-1], and converts back to integer ?
def reverse_string_method(num):
st = str(num)
revst = st[::-1]
ans = int(revst)
return ans
num = 12345
print(reverse_string_method(num))
54321
One-liner Version
num = 12345 reversed_num = int(str(num)[::-1]) print(reversed_num)
54321
Mathematical Approach
This method uses mathematical operations to extract digits from right to left and build the reversed number ?
def reverse_mathematical(num):
rev = 0
while num > 0:
digit = num % 10 # Extract last digit
rev = (rev * 10) + digit # Build reversed number
num = num // 10 # Remove last digit
return rev
num = 12345
print(reverse_mathematical(num))
54321
How It Works
The mathematical method works by:
- Extracting the last digit using modulo operator (
%) - Adding it to the reversed number after shifting existing digits left
- Removing the last digit using integer division (
//) - Repeating until all digits are processed
Handling Negative Numbers
Both methods need modification to handle negative numbers ?
def reverse_with_negative(num):
is_negative = num < 0
num = abs(num) # Work with positive number
# Reverse using string method
reversed_num = int(str(num)[::-1])
return -reversed_num if is_negative else reversed_num
# Test with positive and negative numbers
print(reverse_with_negative(12345)) # 54321
print(reverse_with_negative(-12345)) # -54321
54321 -54321
Comparison
| Method | Pros | Cons |
|---|---|---|
| String Slicing | Simple, readable, handles large numbers | Type conversion overhead |
| Mathematical | No type conversion, pure arithmetic | More complex logic |
Conclusion
Use string slicing for simplicity and readability. Choose the mathematical approach when you need to avoid string conversion or want a pure arithmetic solution.
