Created
May 9, 2023 21:52
-
-
Save codecakes/95eb3c0e987a28e4af444b016438f8ec to your computer and use it in GitHub Desktop.
Count palindrome numbers within a range
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ================ 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