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

前端 未结 21 1483
感情败类
感情败类 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:49

    Yours doesn't work properly since it checks 999*999, then 999*998, then 999*997 until it reaches about 999*583. While it doesn't check 997*995 or something closer to the top which generates a larger number

    function largestPalindrome(){
    
        var arr = [];    
        for(var i =999; i>100; i--){
            for(var j = 999; j>100; j--){
                var mul = j*i;
                if(isPalin(mul)){
                    arr.push(j * i);
                }
            }
        }
    
        return Math.max.apply(Math, arr);
    }
    
    function isPalin(i){
        return i.toString() == i.toString().split("").reverse().join("");
    }
    
    console.log(largestPalindrome());
    

    Here is another approach, store all palindrome generated by 3 numbers in an array, then use Math.max on the array to get the largest palindrome

提交回复
热议问题