Description Title: determining whether an integer is a palindrome. Palindrome correct order (from left to right) and reverse (right to left) reading is the same integer.
Input: 121 Output: True Input: Output false -121
Problem-solving ideas: Obviously, this problem before with a similar reversal string (indicating that it is useful to brush the question about it, after all, the idea of (ง • _ •) ง) .
A thought: violence convert a string
class Solution: def isPalindrome(self, x: int) -> bool: if (x<0): return False else: str_x = str(x) i = 0 j = len(str_x)-1 while (i < j): if (str_x[i] == str_x[j]): i += 1 j -= 1 else: return False return True
After the reference to the wording of the chiefs, they find their own code is far too complex, and his party get. (Continue to practice> ︿ <)
class Solution: def isPalindrome(self, x: int) -> bool: return str(x)[::-1] == str(x)
Thinking two: with reverse text, using the idea of the stack.
Improvements to two ideas: As the first half and the second half of the palindrome reverse number should be the same, so only half can be read at the time of the cycle.
That cycle has been how to determine the half of it? The original number is divided by 10, and then inverted multiplied by the number after the 10, less than the number after the inversion if the original digital / 10 * 10, then the process has a half digits.
class Solution: def isPalindrome(self, x: int) -> bool: if (x < 0 or (x % 10 == 0 and x != 0)): return False rev = 0 while(x>rev): rev = rev*10 + x % 10 x = x//10 if(x == rev or x == rev//10): return True else: return False