1 minute read

Is Integer Palindrome - Elements of Programming Interviews (EPI)

Problem:

Write a program that takes an integer and determines if that integer is a palindrome. 123456 should return False. 123321 should return True

Solution:

The naive and bruteforce solution would be to convert the integer to a string and then compare from both sides, the first and last digits to be equal until the string is exhauasted.

We can improve upon the naive approach by removing the need for a string and instead directly extract the first and last digits by using log10(x) and x % 10.

def is_palindrome_number(x: int) -> bool:
    """Determine if input x is a palindrome i.e: x = 1223221
    should return True and x = 12345 should return False"""
    # 2 ways to do it, one is to divide the integer in half
    # reverse it and check if both halves are equal. (or just
    # reverse the whole integer and check if its equal to original.
    # The way we are doing it is to check if the first digit equals
    # the last digit and keep moving inwards.
    while x:
        first_mask = 10**(math.floor(math.log10(x)) - 1)
        first_digit = x // first_mask
        last_digit = x % 10
        if first_digit == last_digit:
            x -= first_mask * first_mask
            x //= 10
        else:
            return False
    return True