Python Practice › Function Programs › Program 32
Reverse an integer
Write a Python function to reverse an integer, keeping the sign.
Input
1234, -560
Output
4321 -65
Approach
- Reverse the digits of the absolute value and restore the sign.
Solution
def reverse_int(n): sign = -1 if n < 0 else 1 return sign * int(str(abs(n))[::-1]) print(reverse_int(1234), reverse_int(-560))Output
4321 -65
Line by line
Line 2
The sign is stored separately because “-” would end up at the end of the reversed text.
Learn the concept
New to this topic? Read the lesson, then come back.