Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Examples:
121 is a palindrome.-121 is not a palindrome because reading it backward reads as 121-.10 is not a palindrome because reading it backward reads as 01.False if the number is negative.Here’s how the implementation looks:
def isPalindrome(x: int) -> bool:
# Negative numbers are not palindromes
if x < 0:
return False
# Convert number to string
str_x = str(x)
# Compare string with its reverse
return str_x == str_x[::-1]
# Test cases
print(isPalindrome(121)) # Output: True
print(isPalindrome(-121)) # Output: False
print(isPalindrome(10)) # Output: False
print(isPalindrome(0)) # Output: True
n takes O(n) time.Thus, the overall time complexity is O(n), where n is the number of digits in the integer.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?