Reverse an integer

EasyFunction Programs · 32 of 39

Write a Python function to reverse an integer, keeping the sign.

Advertisement
Input
1234, -560
Output
4321 -65

Approach

  1. Reverse the digits of the absolute value and restore the sign.

Solution

Python
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.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More function programs

← All 39 Function Programs