1 minute read

Reverse Digits - Elements of Programming Interviews (EPI)

Problem:

Write a program which takes an integer and returns the integer with its digits reversed. Example: if input is 123456 the output should be 654321.

Solution:

The naive and brute force solution would be to conver the integer into a string and then traverse it in reverse while storing the result in a new string.

Instead of using strings, if we look closely we can realize that if we wanted to extract the last digit from 123456 we can just do 123456 % 10. And if we wanted to shift it by one digit we can simply do 123456 // 10. By using these 2 operations we can easily construct the reversed digit in a result variable by multiplying it by 10 each time and adding the last digit of our input. This is simple enough to not require an example.

def reverse(x: int) -> int:
    """Function to reverse an integer
    if x = 12345 then return 54321"""
    result, neg = (0, 0)
    if x < 0:
        x, neg = (-x, 1)
    while x:
        result = 10 * result + (x % 10)
        x = x // 10
    return -result if neg else result