Search code examples
javascriptpalindrome

My Solution to the Largest Palindrome of the product of two 3 digit numbers needs work


The answer I'm getting is not the correct one (correct answer is 906609). Please help me understand where I am going wrong. I want the while loop to go from 100 to 999 while multiplying itself against the current i value before the loop increments it.

// A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

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

var pali = [];

function palindrome() {
for (var i = 100; i <= 999; i++) {
    var counter = 100;
    
    while (counter <= 999) {
      var result = counter * i;
      if (result.toString() === result.toString().split("").reverse().join("")) {
        pali.push(result);
      }   
      counter++;
    }
}
  return pali[pali.length - 1];
}

console.log(palindrome());


Solution

  • You're going to have to sort the array in ascending order if you want the last one to be the highest:

    pali.sort(function(a, b){return a-b});
    

    Using that, I get 906609.