Skip to content

Instantly share code, notes, and snippets.

@codecakes
Created May 9, 2023 21:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codecakes/95eb3c0e987a28e4af444b016438f8ec to your computer and use it in GitHub Desktop.
Save codecakes/95eb3c0e987a28e4af444b016438f8ec to your computer and use it in GitHub Desktop.
Count palindrome numbers within a range
# ================ Palindrome ==================== #
def is_num_palindrome(num: int) -> bool:
num = abs(num)
while num > 9:
exponent = math.floor(math.log10(num))
msb, remainder = divmod(num, 10 ** exponent)
num, lsb = divmod(remainder, 10)
if msb != lsb:
return False
return True
assert is_num_palindrome(9) == True
assert is_num_palindrome(10) == False
assert is_num_palindrome(121) == True
assert is_num_palindrome(122) == False
assert is_num_palindrome(10_000) == False
assert is_num_palindrome(0) == True
def count_palindrome_numbers(start: int, end: int) -> int:
return sum(is_num_palindrome(num) for num in range(start, end))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment