How to reverse a number in Python
There are several ways to reverse a number in Python. Here is a detailed explanation using three common approaches: converting to a string, mathematical operations, and using recursion.
1. Using String Conversion
The simplest way to reverse a number is by converting it to a string, reversing the string, and then converting it back to a number.
Code Example:
# Input number
num = 12345
# Convert to string, reverse, and convert back to integer
reversed_num = int(str(num)[::-1])
print("Reversed Number:", reversed_num)
Explanation
str(num)
: Converts the number to a string("12345")
.[::-1]
: Slices the string in reverse order("54321")
.int()
: Converts the reversed string back to an integer(54321)
.
2. Using Mathematical Operations
This approach uses arithmetic to reverse the number without converting it to a string.
Code Example:
# Input number
num = 12345
reversed_num = 0
# Loop until the number becomes 0
while num > 0:
digit = num % 10 # Extract the last digit
reversed_num = reversed_num * 10 + digit # Append the digit to the reversed number
num = num // 10 # Remove the last digit from the original number
print("Reversed Number:", reversed_num)
Explanation:
num % 10
: Extracts the last digit of the number.reversed_num * 10 + digit
: Left shifts the digits ofreversed_num
and adds a new digit at the right.num // 10
: Removes the least-significant digit fromnum
.
3. Using Recursion
This method involves a recursive function to reverse the number.
Code Example:
def reverse_number(num, rev=0):
if num == 0:
return rev
else:
digit = num % 10
return reverse_number(num // 10, rev * 10 + digit)
# Input number
num = 12345
reversed_num = reverse_number(num)
print("Reversed Number:", reversed_num)
Explanation:
- The base case is when
num
becomes 0, at which point the reversed number (rev
) is returned. - At each recursive step:
- Get the last digit by using
num % 10
. - Append the digit to
rev
by multiplyingrev
by 10 then adding the digit. - Remove the last digit from
num
by doingnum // 10
.
- Get the last digit by using
Choosing the Right Method
- String Conversion: Simple and rapid for most application scenarios.
- Mathematical Operations: Good for problems where you can’t manipulate strings.
- Recursion: Good for understanding recursion or solving problems programmatically.