Reversing an integer number is an easy task. We may encounter certain scenarios where it will be required to reverse a number. Show Input: 12345 Output: 54321 There are two ways, we can reverse a number −
Convert into string and ReverseThis 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. ExampleLive Demo def reverse(num): st=str(num) revst=st[::-1] ans=int(revst) return ans num=12345 print(reverse(num)) Output54321 Reverse mathematically without converting into stringThis method requires mathematical logic. This method can be used when there is a restriction of not converting the number into string. ExampleLive Demo 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)) Output54321
Updated on 10-Mar-2021 14:12:28
This is a Python Program to reverse a given number. Problem Description The program takes a number and reverses it. Problem Solution 1. Take the value of the integer and store in a variable. Program/Source Code Here is the source code of the Python Program to reverse a given number. n=int(input("Enter number: ")) rev=0 while(n>0): dig=n%10 rev=rev*10+dig n=n//10 print("Reverse of the number:",rev) Program Explanation 1. User must first enter the value and store it in a variable n. Runtime Test Cases Case 1: Enter number: 124 Reverse of the number: 421 Case 2: Enter number: 4538 Reverse of the number: 8354 Sanfoundry Global Education & Learning Series – Python Programs. To practice all Python programs, here is complete set of 150+ Python Problems and Solutions. Next Steps:
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn. Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses. Can you reverse an integer Python?Python makes it easy to reverse a number by using a while loop. We use a while loop with the help of both floor division and the modulus % operator.
How do you reverse a number?Reverse an Integer
In each iteration of the loop, the remainder when n is divided by 10 is calculated and the value of n is reduced by 10 times. Inside the loop, the reversed number is computed using: reverse = reverse * 10 + remainder; Let us see how the while loop works when n = 2345 .
How do you reverse input in Python?Use reversed() Method to Reverse a String in Python
You can also use the reversed method in Python which returns a reversed object or iterator of the input string. The only thing you need to do is to perform an additional join operation on the resultant reversed object and return the new string.
|