Problem 4: Largest palindrome product

Tell us what’s happening:
This code passes for parameter 2 but doesn’t pass for 3. Can anyone tell me why?

Your code so far


function largestPalindromeProduct(digit) {
  // Good luck!
  if(digit === 2) {
    for(let i=99; i>9; i--) {
      for(let j=99; j>9; j--) {
        let number = i * j;
        let str = number.toString();
        if(str === str.split("").reverse().join(""))
          return number;
      }
    }
  }

    for(let i=999; i>99; i--) {
      for(let j=999; j>99; j--) {
        let number = i * j;
        let str = number.toString();
        if(str === str.split("").reverse().join(""))
          return number;
      }
    }

  return undefined;
}

largestPalindromeProduct(3);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/coding-interview-prep/project-euler/problem-4-largest-palindrome-product

It seems to be returning a palindrome but not the largest palindrome…

Yeah, but I am not sure why it’s not returning the largest palindrome though

You haven’t added any code to handle that scenario (the scenario where the first palindrome is not the biggest).

You simply find the first one and return as per the code above.

Instead of just returning. you can store the values and later on, decide which one is the highest that needs to be returned.

1 Like

Thanks that makes sense.

don’t forget to break out of the inner loop though once you find one palindrome as that one will be that largest for the current value of i (since every j value after this will be smaller). Just a tip to save you runtime.

Is this related to Phone lookup services? I have tried White pages which is completed based on this. Let’s have a look on this: http://www.crunchytricks.com/2015/05/best-free-reverse-phone-lookup-services.html

It might be, this is one of the challenges from interview prep course here in FCC.