How to reverse a number in Python

There are different ways to reverse a number in Python. Here are three common methods:

  1. 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 integer num into a string.
  • [::1] is a slicing notation that means to reverse the string.
  • int() converts the reversed string back into an integer.
  1. 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.
  1. 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 number num has only one digit left. If so, it returns that digit.
  • Otherwise, it extracts the last digit last_digit and the remaining digits remaining_digits. The number of digits in remaining_digits is determined by taking the length of the string representation of remaining_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().