Find the largest palindrome made from the product of two 3-digit numbers - Javascript

前端 未结 21 1227
感情败类
感情败类 2020-12-28 17:16

Can anyone tell me what\'s wrong with the code. Find the largest palindrome made from the product of two 3-digit numbers.

function largestPalind         


        
21条回答
  •  礼貌的吻别
    2020-12-28 17:27

    This is how I did it. I used the old fashioned way to check for a palindrome. It appears to run faster on my computer but I may be wrong. Pushing to an array, as in the above post, was definitely very slow on my computer. Noticeable lag at the console. I would recommend just checking to see if your product is greater than your current max, if it is, store that instead of pushing everything to an array. Please feel free to correct me if I'm wrong. Much appreciated.

    //should find the largest palindrome made from the product of two 3 digit numbers
    var largestPalindrome = function() {
    
        var max = 0,
            product = 0;
        for (var num1 = 999; num1 >= 100; num1--) {
            for (var num2 = 999; num2 >= 100; num2--) {
                product = num1 * num2;
                product > max && isPalindrome(product.toString()) ?  max = product : 0;
            }
        }
        return max;
    };
    
    //check to see if product is a palindrome
    var isPalindrome = function(product) {
        var palindromeCheck = true;
        for (var i = 0; i < product.length / 2; i++) {
            if (product[i] != product[product.length - i - 1])
                palindromeCheck = false;
        }
        return palindromeCheck;
    
       //return product === product.split("").reverse().join("");
    };
    

提交回复
热议问题