Given an integer x
, return true
if x
is a palindrome, 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?
This problem asks to determine if an integer is a palindrome. A palindrome reads the same forwards and backward. The efficient approach avoids converting the integer to a string.
Algorithm (Reverse Half):
Handle Special Cases:
false
).false
). This is because a palindrome must have the same first and last digits.Reverse the Second Half: The core idea is to reverse only the right half of the number and compare it to the left half. We don't need to reverse the entire number, which improves efficiency. This is done iteratively:
y
to 0 (to store the reversed number).y
is less than x
.x
using the modulo operator (x % 10
).y
by multiplying y
by 10 and adding the last digit (y = y * 10 + x % 10
).x
by integer division (x //= 10
or x /= 10
).Compare: After the loop, there are two possibilities:
x
and y
are equal (the number was a palindrome with an odd number of digits).x
is equal to y / 10
(the number was a palindrome with an even number of digits).Time Complexity: O(log₁₀(n))
The loop runs approximately half the number of digits in the input integer n
. The number of digits is proportional to log₁₀(n). Therefore, the time complexity is logarithmic with respect to the input number.
Space Complexity: O(1)
The algorithm uses a constant amount of extra space to store variables like x
, y
.
Code Examples (Python):
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0 or (x and x % 10 == 0): #Handle Negative and trailing zero cases
return False
y = 0
while y < x:
y = y * 10 + x % 10
x //= 10
return x == y or x == y // 10 #Check for both even and odd digit palindrome
Other language implementations follow the same logic, varying only in syntax. The core steps of handling special cases, reversing half the number, and comparing remain consistent across all languages.