SoFunction
Updated on 2024-10-29

A short summary of four ways to implement palindromes using python

A palindrome is when a whole number is reversed to equal the original whole number.

Example 1:
 
Input: 121
Output: true
Example 2:
 
Input: -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: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

1: Integer to string, determine whether the integer is a palindrome by subscript comparison

str_x = str(x)
for i in range(0,int(len(str_x)/2)):
  if str_x[i] != str_x[-i-1]:
    return False
return True

2: String slicing operation, str[index:index:step], inside the parentheses are: character start point, end point and step size

str_x = str(x)
return str_x == str_x[::-1]

3: Methods of mathematical computation, comparing and contrasting the values of inverted integers

if x<0:
  return False
temp_x = x;
palindromeNum = 0
while temp_x != 0:
  palindromeNum = palindromeNum*10 + temp_x%10
  temp_x /= 10
return palindromeNum == x

4: integer to string, reverse the string, compare the reversed string with the original string is equal or not

str_x = str(x)
str_y = ""
for i in str_x:
  str_y = i + str_y
return str_y == str_x

Above this summary of four ways to use python to realize the number of back text is all that I have shared with you.