Python Program to reverse a number

In this post, we will see how to reverse a number in python.


Problem

You just need to reverse a number
For example:

14567 —> 76541

There are many ways to reverse a number.

  • Using loop
  • Using string

Using loop

You can use simple while loop as below to reverse a number.

def reverseNumber(num): reverse = 0 while(num > 0): remainder = num %10 reverse = (reverse *10) + remainder num = num /10 return reverse Reverse_Integer(14567)

Output:

76541

Explanation:

  • Initialized variabe reverse=0
  • Iterate via while loop.In each iteration, find the remainder and multiply reverse with 10 and add remainder to it
  • Divide the number by 10 in each iteration to remove most significant digit

Using String

Let’s see a very simple way to reverse a number.
First, convert the number into String and then simply reverse it using String slicing.

number=14567 strNum=str(number) result=strNum[::-1] print(result)

Output:

76541

That’s all about reversing a number in python.

Leave a Reply

Your email address will not be published. Required fields are marked *