9. Palindrome Number easy
Given an integer x
, return true
if x
is a
, and false
otherwise.
Example 1:
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:
Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Constraints:
-231 <= x <= 231 - 1
Follow up: Could you solve it without converting the integer to a string?
Solutions:
a. Convert Integer to String:
class Solution:
def isPalindrome(self, x: int) -> bool:
str_x = str(x)
len_x = len(str_x)
for i in range(len_x):
if str_x[i] != str_x[len_x-i-1]:
return False
return True
or
class Solution:
def isPalindrome(self, x: int) -> bool:
return str(x) == str(x)[::-1]
b. Dont't Convert Integer to String:
class Solution:
# This function checks if a given integer is a palindrome.
def isPalindrome(self, x: int) -> bool:
# Check if the number is negative or a multiple of 10 (excluding 0)
if x < 0 or (x != 0 and x % 10 == 0):
return False
reversed_num = 0
original = x
# Reverse the second half of the number
while x > reversed_num:
reversed_num = reversed_num * 10 + x % 10 # Add the last digit of 'x' to 'reversed_num'
x //= 10 # Remove the last digit of 'x'
# Check if the reversed number matches the original number, x == reversed_num // 10 is when X have odd width
return x == reversed_num or x == reversed_num // 10
标签:10,Palindrome,return,reversed,Number,121,num,str,LeetCode From: https://www.cnblogs.com/millionyh/p/18100520