The reverse of a number using python
Faith Mueni Kilonzi

Faith Mueni Kilonzi @global_codess

About: I am a full-stack software engineer, technical writer, and DevOps enthusiast, with a passion for problem-solving through implementation of high-quality software products. I hold a bachelor’s degree

Location:
Nairobi, Kenya
Joined:
Jan 10, 2020

The reverse of a number using python

Publish Date: Oct 15 '20
6 0

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

Comments 0 total

    Add comment