美文网首页
6 - 9. Palindrome Number

6 - 9. Palindrome Number

作者: bestCindy | 来源:发表于2022-06-20 18:12 被阅读0次

    https://leetcode.com/problems/palindrome-number/

    var isPalindrome = function(x) {
        if (x < 0) return false;
        
        let arr = x.toString().split('');
        let halfArr = arr.slice(0, Math.floor(arr.length / 2));
        
        return halfArr.every((item, index) => item === arr[arr.length - 1 - index]);
        
    };
    

    we can reverse number then check with given number

    var isPalindrome = function(x) {
        if (x < 0) return false;
        
        let result = 0;
        for (let i = x; i >= 1; i = Math.floor(i / 10)) {
            result = result * 10 + i % 10;
        }
        
        return x === result;
    };
    

    using some api with Array

     var isPalindrome = function (x) {
      x = x.toString().split('');
    
      while (x.length > 1) {
        if (x.pop() !== x.shift()) {
          return false;
        }
      }
    
      return true;
    };
    

    相关文章

      网友评论

          本文标题:6 - 9. Palindrome Number

          本文链接:https://www.haomeiwen.com/subject/csmjvrtx.html