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
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
Top comments (0)