Search code examples
javascriptloopspalindrome

Javascript: challenge - not getting the right answer


I'm redoing the Project Euler challenges in Javascript. The task is to get the largest palindrome number (https://projecteuler.net/problem=4). Now I get the following code:

var lpp = 0;
  for (var a = 0; a < 1000; a++) {
    for (var b = 0; b < 1000; b++) {
      var str = (a*b).toString();
      if (str.charAt(0) === str.charAt(5)) {
        if (str.charAt(1) === str.charAt(4)) {
          if (str.charAt(2) === str.charAt(3)) {
            lpp = str;
          }
        }
      }
    }
  }
  console.log(lpp);

The output of the code is 580085, which I know is the wrong answer as I had previously done the challenges in Python.


Solution

  • You're almost there. The problem with your code is that it just stores the last palindrome it finds, which is not necessarily the largest. If we tweak the code a tad and add a check that the current evaluated product is indeed larger than the previously found palindrome, you'll get the correct answer (906609):

    var lpp = 0;
      for (var a = 0; a < 1000; a++) {
        for (var b = 0; b < 1000; b++) {
          var tmp = a*b;
          if (tmp < lpp) {
              continue;
          }
          var str = tmp.toString();
          if (str.charAt(0) === str.charAt(5)) {
            if (str.charAt(1) === str.charAt(4)) {
              if (str.charAt(2) === str.charAt(3)) {
                lpp = tmp;
              }
            }
          }
        }
      }
      console.log(lpp);