w3resource logo


Python Exercises

Python Challenges: Reverse the digits of an integer

Python Challenges - 1: Exercise-18 with Solution

Write a Python program to reverse the digits of an integer.

Input : 234
Input : -234
Output: 432
Output : -432

Explanation :

Python: Reverse the digits of an integer

Sample Solution :-

Python Code :

def reverse_integer(x):
        sign = -1 if x < 0 else 1
        x *= sign

        # Remove leading zero in the reversed integer
        while x:
            if x % 10 == 0:
                x /= 10
            else:
                break

        # string manipulation
        x = str(x)
        lst = list(x)  # list('234') returns ['2', '3', '4']
        lst.reverse()
        x = "".join(lst)
        x = int(x)
        return sign*x
    
print(reverse_integer(234))
print(reverse_integer(-234))

Output :

432                                           
-432 

Flowchart:

Python Flowchart: Reverse the digits of an integer

Python Code Editor:

def reverse_integer(x):
        sign = -1 if x < 0 else 1
        x *= sign

        # Remove leading zero in the reversed integer
        while x:
            if x % 10 == 0:
                x /= 10
            else:
                break

        # string manipulation
        x = str(x)
        lst = list(x)  # list('234') returns ['2', '3', '4']
        lst.reverse()
        x = "".join(lst)
        x = int(x)
        return sign*x
    
print(reverse_integer(234))
print(reverse_integer(-234))

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Solve these problems:

Python: How to check whether a file exists using Python?

C#: Loops in c#

PHP: For each

SQL: JOIN using more than 5 tables

JavaScript: Blank Slide in Javascript Slideshow