Problem
Given an integerx, return true if x is a palindrome, and false otherwise.
Examples
Constraints
- -2^31 <= x <= 2^31 - 1
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 9 with 16 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 9 # by problem number
lcpy gen -s palindrome_number # by problem name
x, return true if x is a palindrome, and false otherwise.
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
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.
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
class Solution:
# Time: O(log10(n)) - process half the digits
# Space: O(1)
def is_palindrome(self, x: int) -> bool:
# Negative numbers and numbers ending in 0 (except 0 itself) are not palindromes
if x < 0 or (x % 10 == 0 and x != 0):
return False
reversed_half = 0
while x > reversed_half:
reversed_half = reversed_half * 10 + x % 10
x //= 10
# Even length: x == reversed_half
# Odd length: x == reversed_half // 10 (drop middle digit)
return x == reversed_half or x == reversed_half // 10
| Time | Space |
|---|---|
| O(log10(n)) - process half the digits | O(1) |