8. Palindrome Number
Given an integer x, return true if x is a palindrome, and false otherwise. An integer is a palindrome when it reads the same forward and backward. For example, 121 is a palindrome while 123 is not.
Examples:
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.Problem Breakdown:
- First, we handle edge cases. Negative numbers are never palindromes because of the negative sign. We can immediately return False for any negative number.
if x < 0: return False- We convert the number to a string so we can easily compare characters from both ends. This is the most straightforward approach.
s = str(x)- We use two pointers - one at the start and one at the end of the string. We compare characters at these positions moving inward.
left = 0 right = len(s) - 1- While left is less than right, we compare the characters. If they ever differ, the number is not a palindrome and we return False.
while left < right: if s[left] != s[right]: return False left += 1 right -= 1- If we make it through the entire comparison without finding a mismatch, the number is a palindrome and we return True.
return True
Summary:
Convert the number to a string and use two pointers to compare characters from both ends moving toward the center. Negative numbers are automatically not palindromes. If all character pairs match, the number is a palindrome.
Time and Space Complexity:
Time Complexity: O(n) - where n is the number of digits in the number, we compare half the digits.
Space Complexity: O(n) - we create a string representation of the number.
Python Solution:
def isPalindrome(x):
if x < 0:
return False
s = str(x)
left = 0
right = len(s) - 1
while left < right:
if s[left] != s[right]:
return False
left += 1
right -= 1
return TrueJavaScript Solution:
var isPalindrome = function(x) {
if (x < 0) return false;
const s = String(x);
let left = 0;
let right = s.length - 1;
while (left < right) {
if (s[left] !== s[right]) return false;
left++;
right--;
}
return true;
};Java Solution:
class Solution {
public boolean isPalindrome(int x) {
if (x < 0) return false;
String s = String.valueOf(x);
int left = 0;
int right = s.length() - 1;
while (left < right) {
if (s.charAt(left) != s.charAt(right)) return false;
left++;
right--;
}
return true;
}
}