In this post, I’m going to walk you through how to check if an integer is a palindrome in JavaScript. This is a classic coding question often used in interviews, and while it’s rarely something you’ll need in real-world development, it does test your understanding of data manipulation and optimization techniques.
We’ll cover two methods here: a simple string-based approach and a more efficient mathematical approach that avoids string manipulation altogether. Each has its own use case and gives you different ways to think about the problem.
What is a Palindrome?
A palindrome is a sequence that reads the same forward and backward. So, numbers like 121 and 1221 are palindromes, while 123 and -121 are not. For integers, keep in mind:
• Negative numbers are not palindromes because of the – sign.
• Numbers ending in 0 (except 0 itself) also can’t be palindromes, like 10 or 120, since they’d need a leading zero to match the reverse.
Approach 1: The Simple String Conversion Solution
The most straightforward way to check if a number is a palindrome is to treat it as a string and check if the reversed string matches the original. Here’s how:
function isPalindrome(x) {
// Negative numbers are not palindromes
if (x < 0) return false;
// Convert the integer to a string
const str = x.toString();
// Reverse the string and check if it matches the original
return str === str.split('').reverse().join('');
}
Explanation:
1. Negative Check: If x is negative, we immediately return false since the – makes it impossible for a number to mirror itself.
2. Convert to String: x.toString() converts the number to a string so we can reverse it.
3. Reverse and Compare: Using .split(”).reverse().join(”), we reverse the string and check if it matches the original. If it does, the number is a palindrome.
Example Walkthroughs
Let’s look at a couple of examples:
• Example 1: x = 121
• 121 converts to “121”.
• Reversing “121” gives “121”, which matches the original, so true.
• Example 2: x = -121
• Since x < 0, we return false immediately.
• Example 3: x = 10
• “10” reversed becomes “01”, so 10 is not a palindrome, and we return false.
Time Complexity
• Time Complexity: O(n), where n is the number of digits, because converting to a string and reversing it both require iterating over all characters.
• Space Complexity: O(n) as well, since we create an additional string when reversing.
Approach 2: The Efficient Mathematical Solution
For larger numbers, or if you want to avoid extra space, we can check if a number is a palindrome without converting it to a string. The idea here is to reverse only half of the digits and see if they match the other half.
Here’s the code:
function isPalindrome(x) {
// Negative numbers and numbers ending in 0 (but not 0 itself) are not palindromes
if (x < 0 || (x % 10 === 0 && x !== 0)) return false;
let reversedHalf = 0;
while (x > reversedHalf) {
// Get the last digit of x and add it to reversedHalf
reversedHalf = reversedHalf * 10 + x % 10;
// Remove the last digit from x
x = Math.floor(x / 10);
}
// Check if the original half equals the reversed half
return x === reversedHalf || x === Math.floor(reversedHalf / 10);
}
Explanation:
1. Initial Checks:
• If x is negative, return false because negative numbers aren’t palindromes.
• If x ends in 0 but is not 0, it can’t be a palindrome (e.g., 10 is not a palindrome).
2. Reverse Half of the Digits:
• We create a variable, reversedHalf, to store the reverse of the last half of x.
• We keep appending the last digit of x to reversedHalf (using x % 10) and then remove that digit from x by dividing it by 10.
• This continues until reversedHalf becomes greater than or equal to x, which means we’ve reversed half of the digits.
3. Comparison:
• For even-digit numbers, x should equal reversedHalf.
• For odd-digit numbers, the middle digit doesn’t affect the palindrome, so we check if x equals Math.floor(reversedHalf / 10).
Example Walkthroughs
• Example 1: x = 1221
• After reversing half the digits, x = 12 and reversedHalf = 12.
• Since x === reversedHalf, we return true.
• Example 2: x = 12321
• After reversing half the digits, x = 12 and reversedHalf = 123.
• Since x === Math.floor(reversedHalf / 10), we return true.
Time Complexity
• Time Complexity: O(log₁₀(n)), where n is the value of x. We only reverse half the digits, so the number of steps is proportional to the number of digits (logarithmic).
• Space Complexity: O(1) because we only use a few integer variables.
Conclusion: Which Approach is Better?
The mathematical approach is the winner in terms of efficiency. It’s both faster and more space-efficient, especially for large numbers. That said, the string-based approach is still a simple and valid solution, especially when the input size is small.
In an interview, the string solution might be fine for simplicity, but if optimization is important, go with the mathematical approach. Hopefully, this helps clear up both methods and gives you a solid answer if you encounter this in an interview. Happy coding!