To solve this problem, we need to determine if a given number is a palindrome. A palindrome number reads the same forwards and backwards. Negative numbers cannot be palindromes because the minus sign would not appear at both ends.
Approach 1: String Conversion (Concise)
This approach converts the number to a string and checks if the string is equal to its reverse. This method is straightforward and easy to understand.
Steps:
- If the number is negative, return
Falseimmediately. - Convert the number to a string.
- Check if the string is the same as its reverse.
Solution Code (String Conversion)
def is_palindrome(n):
"""Check if a number is a palindrome using string reversal."""
if n < 0:
return False
s = str(n)
return s == s[::-1]
Approach 2: Mathematical Operations (No String Conversion)
This approach reverses the digits of the number using mathematical operations and compares the reversed number to the original. This method avoids string conversion and is more algorithmic.
Steps:
- If the number is negative, return
False. - Store the original number.
- Reverse the digits of the number using modulo and integer division.
- Compare the reversed number with the original number.
Solution Code (Mathematical Operations)
def is_palindrome(n):
"""Check if a number is a palindrome using mathematical operations."""
if n < 0:
return False
original = n
reversed_num = 0
while n > 0:
reversed_num = reversed_num * 10 + (n % 10)
n = n // 10
return original == reversed_num
Explanation
- String Conversion: This method leverages Python's string slicing (
s[::-1]) to reverse the string. It is efficient and concise, making it ideal for most cases. - Mathematical Operations: This method reverses the number by extracting digits (using
n%10) and building the reversed number (usingreversed_num *10 + digit). It is useful if string conversion is not preferred.
Both methods correctly handle edge cases like 0 (returns True), 10 (returns False), and negative numbers (returns False). Choose the approach that best fits your needs!
Examples:
is_palindrome(121)→Trueis_palindrome(-121)→Falseis_palindrome(10)→Falseis_palindrome(0)→True
The output for each function call is as expected, confirming correctness.

作者声明:本文包含人工智能生成内容。