In this method, we convert the integer to a string and check if it reads the same forwards and backwards. This approach is straightforward and leverages the built-in string operations.
Time Complexity: O(n), where n is the length of the string representation of the number.
Space Complexity: O(n) for the string conversion.
1function isPalindrome(x) {
2 if (x < 0) return false;
3 const str = x.toString();
4 const n = str.length;
5 for (let i = 0; i < n / 2; i++) {
6 if (str[i] !== str[n - i - 1]) return false;
7 }
8 return true;
9}
10
The function converts the integer to a string and compares corresponding characters from the start and the end of the string. If they match all the way towards the center, we return true, indicating that the number is a palindrome.
This approach avoids the use of string conversions by reversing half of the digits of the number and comparing the two halves. This is more memory efficient as it only creates a few integer variables.
Time Complexity: O(log10(n)), where n is the input number because we are dividing the number by 10 in each iteration.
Space Complexity: O(1) because no additional space proportional to input size is used.
1public class Solution {
2 public boolean isPalindrome(int x) {
3 if (x < 0 || (x % 10 == 0 && x != 0)) return false;
4 int reversedHalf = 0;
5 while (x > reversedHalf) {
6 reversedHalf = reversedHalf * 10 + x % 10;
7 x /= 10;
8 }
9 return x == reversedHalf || x == reversedHalf / 10;
10 }
11}
12
The solution handles edge cases for negative numbers and zero-ending numbers. It constructs a reversed version of the last half of the digits using arithmetic to extract and append digits. It finally compares the two halves.