Home > Enterprise >  Why does my solution not work in LeetCode?
Why does my solution not work in LeetCode?

Time:12-22

while I try my solution for the given example it fails at the leetcode although it provide the expected output at my VScode

Given an integer x, return true if x is a palindrome and false otherwise.

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.

my answer

/**
 * @param {number} x
 * @return {boolean}
 */
var isPalindrome = function(x) {
    if (Math.sign(x) === -1) {
        console.log("false")
        return "false";

    } else {
        let y = x.toString(); // convert the number to string 
        let strArray = y.split('') // convert the string to array of strings
        let reversed = strArray.reverse() // reverse the array 
        let convString = reversed.join('') // convert the array to string 
        let revX = parseInt(convString)
        if (x === revX) {
            return "true"
        } else {
            return "false"
        }
    }
};

the leetcode test didn`t pass my solution while it pass when i test it myself

CodePudding user response:

your solution is correct, your solution not passing the tests on LeetCode because you are returning the strings "true" and "false" instead of the boolean values true and false. Try modifying your solution to return the boolean values true and false instead of the string values "true" and "false", and see if that helps.

    if (x === revX) {
        return true
    } else {
        return false
    }

The issue with your solution is that when you return "false", it is a string with a valid length, which makes it always considered as a positive value. This is why your solution appears to be working correctly when you test it manually and see the output, but it is not working when you submit it to LeetCode. The computer is evaluating the type of the value, not the word itself, so you should return the boolean values true and false instead of the string values "true" and "false".

your whole code should be like this

var isPalindrome = function(x) {
    if (Math.sign(x) === -1) {
        console.log("false")
        return false;

    } else {
        let y = x.toString(); // convert the number to string 
        let strArray = y.split('') // convert the string to array of strings
        let reversed = strArray.reverse() // reverse the array 
        let convString = reversed.join('') // convert the array to string 
        let revX = parseInt(convString)
        if (x === revX) {
            return true
        } else {
            return false
        }
    }
};
  • Related