DEV Community

loading...

The reverse of a number using python

Faith Mueni Kilonzi
I am a curious software engineer and a data science enthusiast, with a passion for problem-solving through the implementation of high-quality software products. I enjoy learning and teaching.
・1 min read

Given a number, reverse its digits and print the new number.
For example:
Input : num = 8972
Output: 2798

There are a couple of ways to solve this:

1. Reverse Number using String slicing

We convert the given number to string using str()
Reverse it using string slicing
Convert the reversed string to int and return the int.

def reverseNumber(n):
    reversed_number = int(str(n)[::-1])
    return reversed_number
Enter fullscreen mode Exit fullscreen mode

2. Reverse Number using While Loop

Using a while loop, iterate through the list of the digits from the last one and append the digits into a new number.

def reverseNumber(n):
    reversed_number = 0
    while(n!=0):
        r=int(n%10)
        reversed_number = reversed_number*10 + r
        n=int(n/10)                    
    return reversed_number
Enter fullscreen mode Exit fullscreen mode

Discussion (0)