5 Best Ways to Reverse a Number in Python

Rate this post

πŸ’‘ Problem Formulation: Reversing a number is a common task in programming that involves transforming a number such as 12345 into its backward sequence, like 54321. In Python, this can be achieved with a variety of methods. This article will guide you through five different ways to reverse an integer in Python, detailing the process and providing examples for each method.

Method 1: Using String Conversion and Slicing

Reversing a number by converting it to a string is the most straightforward method. Simply convert the integer to a string with str(), and then apply slicing with [::-1] to reverse it. Lastly, convert it back to an integer using int().

Here’s an example:

number = 12345
reversed_number = int(str(number)[::-1])
print(reversed_number)

Output:

54321

This code takes an integer, converts it to a string to reverse the characters using slicing, and then casts it back to an integer to obtain the reversed number.

Method 2: Using a While Loop

To reverse a number with a while loop, you extract each digit starting from the end by using modulus and division operations and building the reverse number step by step.

Here’s an example:

number = 12345
reversed_number = 0
while number != 0:
    digit = number % 10
    reversed_number = reversed_number * 10 + digit
    number //= 10
print(reversed_number)

Output:

54321

This snippet repeatedly divides the number by 10 to peel off the last digit and adds it to the reversed number, which is being constructed by multiplying by 10 and adding the next digit.

Method 3: Using Recursion

Reversing a number recursively involves creating a function that calls itself with progressively smaller portions of the number until it is fully reversed.

Here’s an example:

def reverse_number(n, reversed_n=0):
    if n == 0:
        return reversed_n
    else:
        return reverse_number(n // 10, reversed_n * 10 + n % 10)

number = 12345
print(reverse_number(number))

Output:

54321

Through each recursion call, the last digit of the number is processed and appended to the reversed number, which is passed along until the base condition is met.

Method 4: Using the reversed() Function and join()

Python’s in-built reversed() function can be applied to a sequence. Here, the number is converted to a string, which is then reversed by reversed() and finally concatenated back into a single string with join(), and turned back into an integer.

Here’s an example:

number = 12345
reversed_number = int(''.join(reversed(str(number))))
print(reversed_number)

Output:

54321

The reversed() function returns an iterator that accesses the given string in reverse order, which join() then merges into a new string. The result is cast back to an integer.

Bonus One-Liner Method 5: Using reduce() Function

The reduce() function can also reverse an integer by applying a lambda function that accumulates the reverse number, with each digit extracted using modulus and division operations.

Here’s an example:

from functools import reduce

number = 12345
reversed_number = reduce(lambda acc, x: acc*10 + x, map(int, str(number)))
print(reversed_number)

Output:

54321

In this one-liner, map() turns each character of the stringified number into an integer, which reduce() accumulates into the reversed number.

Summary/Discussion

  • Method 1: String Conversion and Slicing. Strength: Simple and clean. Weakness: Requires two type conversions.
  • Method 2: While Loop. Strength: Efficient memory usage. Weakness: Slightly less readable due to loop control.
  • Method 3: Recursion. Strength: Elegant functional solution. Weakness: Risk of stack overflow for very large numbers.
  • Method 4: reversed() Function and join(). Strength: Utilizes built-in functions for readability. Weakness: Involves multiple function calls and conversions.
  • Bonus Method 5: reduce() Function. Strength: Compact one-liner solution. Weakness: Can be less intuitive for those unfamiliar with functional programming.