Reverse digits

Write a program which takes an integer and returns the integer corresponding to the digits of the input written in reverse order. For example, the reverse of 42 is 24 and the reverse of -314 is -413.

Brute force approach:

def reverse_digits_brute_force(i):
    is_negative, i = i < 0, abs(i)
    result = ''.join(reversed(str(i)))
    return int('-' + result if is_negative else result)

However, let’s avoid casting to a string. Instead, let’s use the modulus operator and a spare integer to represent our new result.

def reverse_digits(i):
    result, i_remaining = 0, abs(i)
    while i_remaining:
        result = result * 10 + i_remaining % 10
        i_remaining //= 10
    return -1 * result if i < 0 else result

This solution runs in O(n) time, where n is in the number of digits in i.