JavaScript Solution O(log10(x)/2)


  • 0
    R
    /**
     * @param {number} x
     * @return {boolean}
     */
    var isPalindrome = function(x) {
      if (typeof x !== 'number' || x < 0 || x !== Math.trunc(x)) {
        return false;
      }
    
      if (x < 10) {
        return true;
      }
    
      var length = Math.trunc(Math.log10(x)) + 1;
      var middleIndex = Math.floor(length / 2);
    
      for (var i = 0; i <= middleIndex; i++) {
        var coeficcient = Math.pow(10, length - i * 2 - 1);
        var lastDigit = x % 10;
        var firstDigit = Math.trunc(x / coeficcient);
    
        if (lastDigit !== firstDigit) {
          return false;
        }
    
        x = Math.trunc((x - coeficcient * firstDigit) / 10);
      }
    
      return true;
    };
    

Log in to reply
 

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