Write a python function to check if an integer is a palindrome without converting to a str
- User
Write a python function to check if an integer is a palindrome without converting to a str
- Assistant
Sure! To check if an integer is a palindrome without converting it to a string, you can reverse the integer by computing its remainder with 10 (to get the last digit), and then by progressively removing the last digit through integer division by 10. Here is how you could implement such a function in Python:
def is_palindrome(num): # Negative numbers and numbers ending with 0 are not palindromes, # except for 0 itself. if num < 0 or (num % 10 == 0 and num != 0): return False reversed_num = 0 while num > reversed_num: # Get the last digit and add it to the reversed number's correct position reversed_num = reversed_num * 10 + num % 10 # Remove the last digit from the original number num //= 10 # A number is a palindrome if it is equal to its reverse # or if it's equal when removing the last digit from the reversed number # (for odd-length numbers) return num == reversed_num or num == reversed_num // 10 # Examples print(is_palindrome(121)) # True print(is_palindrome(-121)) # False print(is_palindrome(10)) # False print(is_palindrome(12321)) # True