There are different ways to reverse a number in Python. Here are three common methods:
- Using strings:
One way to reverse a number is to convert it into a string, then reverse the string, and finally convert the reversed string back into an integer. Here’s an example:
num = 12345 reversed_num = int(str(num)[::-1]) print(reversed_num)
Output:
54321
Explanation:
str(num)
converts the integernum
into a string.[::1]
is a slicing notation that means to reverse the string.int()
converts the reversed string back into an integer.
- Using math:
Another way to reverse a number is to use math operations. Here’s an example:
num = 12345 reversed_num = 0 while num > 0: remainder = num % 10 reversed_num = (reversed_num * 10) + remainder num = num // 10 print(reversed_num)
Output:
54321
Explanation:
- In each iteration of the loop, the remainder of the current number divided by 10 is extracted using the modulo operator
%
. - The reversed number is constructed by adding the remainder to the previous reversed number multiplied by 10. This works because multiplying by 10 shifts the digits of the reversed number to the left, leaving the units place free for the new digit.
- Finally, the original number is divided by 10 (using integer division
//
) to remove the units place digit that was just processed.
- Using recursion:
A third way to reverse a number is to use a recursive function that extracts the last digit of the number and adds it to the reversed version of the remaining digits. Here’s an example:
def reverse_num(num): if num < 10: return num else: last_digit = num % 10 remaining_digits = num // 10 return (last_digit * 10**(len(str(remaining_digits))) + reverse_num(remaining_digits)) num = 12345 reversed_num = reverse_num(num) print(reversed_num)
Output:
54321
Explanation:
- The function
reverse_num()
checks whether the input numbernum
has only one digit left. If so, it returns that digit. - Otherwise, it extracts the last digit
last_digit
and the remaining digitsremaining_digits
. The number of digits inremaining_digits
is determined by taking the length of the string representation ofremaining_digits
. - The function returns the concatenation of the last digit multiplied by 10 to the power of the number of remaining digits, and the reversed version of the remaining digits, which is computed recursively by calling
reverse_num()
.