9. Palindrome Number
Дано целое число x, вернуть true, если x является палиндромом, и false в противном случае.
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.
/**
 * @param {number} x
 * @return {boolean}
 */
var isPalindrome = function(x) {
    // your code...
};
Решение (String-based reversal)
Самое простое решение через разделение строки на массив символов, реверс полученного массива, склейка и сравнение с оригиналом.
const isPalindrome = function(x) {
    const original = String(x);
    const reversed = original.split('').reverse().join('');
    return original === reversed;
};
Вы можете немного улучшить производительность, выполнив несколько общих проверок на палиндромы, чтобы исключить все, что не будет работать, например, числа меньше 0 или числа больше 0, которые делятся на 10.
Но если вы действительно хотите увидеть прирост производительности, лучше отказаться от использования массивов и применить более математическое решение.
Решение (Two pointer method)
In this solution, we will take care of some of the simple cases before writing out logic. Once those are taken care of, we will follow the two-pointer method to check if the number is a palindrome.

The idea is, we will take one digit from the start, and another from the last. Check if both are equal if not, the number is not a palindrome.

Давайте рассмотрим простую реализацию вышеприведенной логики.
var isPalindrome = function(x) {
    if (x < 0) {
        return false;
    }

    if (x < 10) {
        return true;
    }

    if (x % 10 === 0 && x !== 0) {
        return false;
    }

    const str = String(x);
    let i = 0;
    let j = str.length - 1;

    while (i < j) {
        if (str[i] !== str[j]) {
            return false;
        }

        i++;
        j--;
    }

    return true;
};
Сначала позаботимся о следующих кейсах
  • if X is negative ( not a palindrome )
  • if X is less than ten ( always a palindrome )
  • if X has 0 at its last digit and X is not 0 itself ( not a palindrome ) e.g. 10, 130 whose reverse will be 01, 031 respectively
Далее, следующая логика
  • convert the number to a string
  • take two pointers, at the start and end of the string
  • if the digits at both pointers are different, it's not a palindrome
  • we increment starting pointer and decrement the end pointer iteratively
  • if the loop exits, then it was a palindrome
Это все, что нам нужно для решения задачи.

Time and space complexityTime complexity
We see a bit of improvement in run time. We are running logic only for positive numbers greater than 9. Also, in the loop, we are taking two steps instead of 1. However, asymptotically the running time complexity is still O(len x).

Space complexity
We have a number as input, using a couple of more temporary variables, so space complexity is constant, O(1).