Javascript solution (can i simplify?)


  • 0
    S
    /**
     * @param {number} x
     * @return {boolean}
    */
    var isPalindrome = function(x) {
      if (!isNaN(x)) {
          x = x.toString();
      }
    
       y = x.split("").reverse().join("");
    
       if (x === y) {
          return true;
       } else {
          return false;
       }
    };
    

    Time: 776ms;

    How can i make this better?


  • 2
    L
    var isPalindrome = function(x) {
        return x === +x.toString().split('').reverse().join('');
    };

  • 0

    Is === + actually better for this problem than

    return x == x.toString().split('').reverse().join('');
    

    (which also gets accepted) or do you just do it because it's better in general? (I'm rather unfamiliar with Javascript)


  • 0
    L

    '===' is safier option for comapring vars, because it also compares their type, good practice is to use '===' instead of '==', that will help you to track vars type and prevent many errors.
    In this case there is almost no difference, just good practice.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.