easy: int palindromes

Problem:

Given an integer x, return true if x is palindrome integer.

An integer is a palindrome when it reads the same backward as forward.

using strings
num = str(x)
head = 0
tail = len(num) - 1

while head < tail:
    # return false if the values at head and tail don't match
    if num[head] != num[tail]:
        return False

    # increment head, decrement tail
    head += 1
    tail -= 1

return True
without using strings
# return false if negative
if x < 0:
    return False

# return True if zero
if x == 0:
    return True

# return false if multiple of 10, ends in 0
if x % 10 == 0:
    return False

# store the original and initialize the inverse
original = x
inverse = 0

while x > 0:
    inverse = (inverse * 10) + (x % 10)
    x //= 10

return original == inverse

Subscribe to rohp

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe