9. Palindrome Number

Resuelto en: 23 jul 2025 🇺🇸

Primera solución fea

6ms Runtime | Superior al 68.49%

var isPalindrome = function(x) {
    const numberToString = String(x);
    const reversedString = [...numberToString].reverse().join("");
    if(reversedString !== numberToString) {
        return false
    } else return true
};
var isPalindrome = function(x) {
    const numberToString = String(x); // Convertimos el número a string
    // Convertimos el string a un array, lo invertimos y lo volvemos a unir en un string
    // Esta línea desperdicia mucho tiempo, lo siento
    const reversedString = [...numberToString].reverse().join("");
    if(reversedString !== numberToString) { // Finalmente comparamos las dos strings
        return false
    } else return true
};

Segunda solución, que terminó siendo peor que la primera aunque yo pensaba que sería mejor

8ms Runtime | Superior al 48.30%

var isPalindrome = function(x) {
    const s = String(x);
    const length = s.length;
    let left = 0;
    let right = length -1;
    while(left <= right) {
        if(s[left] === s[right]) {
            left++
            right--;
        } else {
            return false;
        }
    }
    return true;
};

Why is this a worse solution?


/*
    Mi proceso de pensamiento con esta fue que solo estamos usando un loop, en vez de crear
    un string, luego convertirlo en un array, luego invertirlo, luego crear un string de nuevo...
*/
var isPalindrome = function(x) {
    //Convertimos el número a string, y aquí es donde todo se va abajo
    //Una conversión a string está alojando memoria innecesaria, en especial si el numero es muy grande
    const s = String(x);

    //El resto de esto-basado en mi experiencia-es bastante peformant
    const length = s.length; // Obtenemos la longitud, no queremos ir a s.length en cada iteración
    let left = 0; //Un puntero para la izquierda
    let right = length -1; //Un puntero para la derecha
    while(left <= right) { //Si se encuentran, terminamos y devolvemos true
        if(s[left] === s[right]) { //Si son iguales seguimos avanzando
            left++
            right--;
        } else {
            return false;
        }
    }
    return true;
};

Tercera solución/la mejor (pero no por mucho)

5ms Runtime | Superior al 79.57%


/*
    En realidad estoy impresionado porque aunque esta es una solución matemática
    que no requiere conversión a string, solo es un poco mejor que mi primera solución,
    así que me siento un poco derrotado jeje
*/

var isPalindrome = function(x) {
    if (x < 0 || (x % 10 === 0 && x !== 0)) return false;
    let reversed = 0;
    while (x > reversed) {
        reversed = reversed * 10 + x % 10;
        x = Math.floor(x / 10);
    }
    return x === reversed || x === Math.floor(reversed / 10);
};

var isPalindrome = function(x) {
    if (x < 0 || (x % 10 === 0 && x !== 0)) return false; // Los números negativos o los que terminan en 0 (excepto el 0) no pueden ser palíndromos
    let reversed = 0; // Creamos una variable que va a guardar la mitad del numero
    while (x > reversed) { // Solo procesamos hasta invertir la mitad de los dígitos
        reversed = reversed * 10 + x % 10; // Añadimos el último dígito de x a reversed
        x = Math.floor(x / 10); // Quitamos el último dígito de x
    }
    return x === reversed || x === Math.floor(reversed / 10); // Comprobamos para números de longitud par e impar
};