Reversing a number in Python can be done in various ways. Below are several methods to reverse a number in Python.
1. Converting the Number to a String
The simplest way to reverse a number is to convert it to a string, reverse the string, and then convert it back to an integer.
Example:
# Reversing a number by converting it to a string
num = 12345
reversed_num = int(str(num)[::-1])
print(reversed_num)
Output:
54321
In this example, the number 12345
is converted to the string "12345"
, which is then reversed to "54321"
and converted back to the integer 54321
.
2. Reversing a Number Using a While Loop
You can reverse a number mathematically by using a while loop. This method involves repeatedly extracting the last digit of the number and appending it to a new reversed number.
Example:
# Reversing a number using a while loop
num = 12345
reversed_num = 0
while num > 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num = num // 10
print(reversed_num)
Output:
54321
In this example, the number 12345
is reversed by repeatedly extracting the last digit and building the reversed number.
3. Using Recursion to Reverse a Number
Another method to reverse a number is by using recursion, which involves calling a function within itself.
Example:
# Reversing a number using recursion
def reverse_number(num, rev=0):
if num == 0:
return rev
else:
return reverse_number(num // 10, rev * 10 + num % 10)
num = 12345
reversed_num = reverse_number(num)
print(reversed_num)
Output:
54321
In this example, the reverse_number
function reverses the number 12345
recursively by extracting digits and constructing the reversed number.
4. Using the map()
and join()
Functions
You can also reverse a number by converting it to a string, mapping each character back to an integer, and then joining them in reverse order.
Example:
# Reversing a number using map() and join()
num = 12345
reversed_num = int(''.join(map(str, reversed(str(num)))))
print(reversed_num)
Output:
54321
In this example, the number is first converted to a string, reversed, and then mapped back to a string before converting it to an integer.