9. Palindrome Number
Given an integer x, decide whether it is a palindrome, that is, whether its decimal digits read exactly the same left to right as they do right to left. Return true when they match and false otherwise (printed lowercase).
A negative integer is never a palindrome: the leading minus sign has no counterpart on the right end, so for example -121 reads as 121- reversed and fails. Single-digit numbers, including 0, are always palindromes. The natural follow-up is: can you solve it without converting the number to a string?
Example 1:
Input: x = 121
Output: true
Explanation: Reading 121 backwards gives 121, so it is a palindrome.
Example 2:
Input: x = -121
Output: false
Explanation: Reversed, -121 reads as 121-, which differs from -121, so it is not a palindrome.
Example 3:
Input: x = 10
Output: false
Explanation: Reversed, 10 reads as 01 which is 1, not equal to 10, so it is not a palindrome.
Constraints:
- -2³¹ ≤ x ≤ 2³¹ - 1
- x fits in a 32-bit signed integer.
Hints:
A negative number always has a leading '-' with no match at the other end, so it can never be a palindrome.
The string approach is easy: compare the digit string with its reverse. Can you avoid the string entirely?
Reverse only the second half of the number. When the reversed tail meets or passes the shrinking front half, compare the two, handling the odd-length case by dropping the middle digit.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: x = 121
Expected output: true