Article Directory
1. Topic introduction
2. Code combat
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
x_str = str(x)
left = 0
right = len(x_str) - 1
while left < right:
if x_str[left] != x_str[right]:
return False
left += 1
right -= 1
return True
- class Solution:: defines a class named Solution.
- def isPalindrome(self, x: int) -> bool:: defines a method called isPalindrome, which accepts an integer x as a parameter and returns a Boolean value indicating whether it is a palindrome.
- if x < 0:: If x is a negative number, return False directly, because a negative number cannot be a palindrome.
- x_str = str(x): Convert the integer x to a string for subsequent comparison.
- left = 0 and right = len(x_str) - 1: initialize the left and right pointers, left points to the beginning of the string, right points to the end of the string.
- while left < right:: enter the loop, the loop condition is that the left pointer is smaller than the right pointer, that is, the entire string has not been compared.
- if x_str[left] != x_str[right]:: If the character pointed by the left pointer is not equal to the character pointed by the right pointer, it means that it is not a palindrome and returns False directly.
- left += 1 and right -= 1: Move the left pointer one bit to the right and the right pointer one bit to the left respectively, and continue to compare the next character.
- After the loop ends, it means that the comparison of the entire string is completed, and no unequal characters are found, and True is returned, indicating that it is a palindrome.
This code converts the integer to a string, and then uses the double pointer method to compare from both ends of the string to the middle to determine whether it is a palindrome. If unequal characters are found during the comparison, False is returned directly, otherwise True is finally returned, indicating that it is a palindrome number.
The results are displayed as follows: