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

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

    A bit more optimized version with comments included. Notice, there is no need of fast return, just store the max and optimize the cycles to not recalculate j*i if i*j has already been checked.

    function largestPalindrome() {
    
        var max = 0;
    
        // not using i >= 100 since 100*100 is not palindrome! :)
        for (var i = 999; i > 100; i--) {
            // because i * j === j * i, no need of both i and j
            // to count down from 999
            for (var j = i; j > 100; j--) {
                var mul = j * i;
                if (isPalin(mul) && mul > max) {
                    max = i * j;
                }
            }
        }
    
        return max;
    
    }
    
    function isPalin(i) {
    
        // adding empty string to i instead using of .toString
        // avoids unnecessary wrapping in String object on the left side
        i = '' + i;
    
        // don't rely on ==,  use === instead
        return i === i.split("").reverse().join("");
    
    }
    
    console.log(largestPalindrome());
    

提交回复
热议问题