DEV Community

Faith Mueni Kilonzi
Faith Mueni Kilonzi

Posted on


The reverse of a number using python

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
        reversed_number = reversed_number*10 + r
    return reversed_number
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.