
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to reverse a number in Python?
Reversing an integer number is an easy task. We may encounter certain scenarios where it will be required to reverse a number.
Input: 12345 Output: 54321
There are two ways, we can reverse a number −
Convert the number into a string, reverse the string and reconvert it into an integer
Reverse mathematically without converting into a string
Convert into string and Reverse
This method of reversing a number is easy and doesn’t require any logic. We will simply convert the number into string and reverse it and then reconvert the reversed string into integer. We can use any suitable method for reversing the string.
Example
def reverse(num): st=str(num) revst=st[::-1] ans=int(revst) return ans num=12345 print(reverse(num))
Output
54321
Reverse mathematically without converting into string
This method requires mathematical logic. This method can be used when there is a restriction of not converting the number into string.
Example
def reverse(num): rev=0 while(num>0): digit=num%10 rev=(rev*10)+digit num=num//10 return rev num=12345 print(reverse(num))
Output
54321
- Related Articles
- How to reverse a string in Python?
- How to reverse a string in Python program?
- How to create reverse of a number in R?
- Python program to reverse bits of a positive integer number?
- How to reverse the objects in a list in Python?
- Reverse a number in JavaScript
- C++ Program to Reverse a Number
- Java Program to Reverse a Number
- Swift Program to Reverse a Number
- Haskell Program to Reverse a Number
- Kotlin Program to Reverse a Number
- Reverse a Number in PL/SQL
- Program to reverse a linked list in Python
- Python program to Reverse a range in list
- Write a Golang program to reverse a number

Advertisements