[Leetcode Brush Questions] Algorithm: Palindrome Number

1. Topic introduction

insert image description here

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 
  1. class Solution:: defines a class named Solution.
  2. 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.
  3. if x < 0:: If x is a negative number, return False directly, because a negative number cannot be a palindrome.
  4. x_str = str(x): Convert the integer x to a string for subsequent comparison.
  5. 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.
  6. 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.
  7. 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.
  8. 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.
  9. 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:

insert image description here

Guess you like

Origin blog.csdn.net/wzk4869/article/details/130733339