Problem 4: Largest palindrome product

Problem 4: Largest palindrome product
0

#1

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


#2

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


#3

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


#4

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.


#5

Thanks that makes sense.


#6

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.