OK, a couple of issues here:
My algorithm is for example if n = 2 so the first value is 99
Good logic. Instead of looping and multiplying by 10, you could have used Math.pow
or the new **
operator, but it still gets the right number.
99 /99 then 99/98 and so one
it countinues looping if I did not find the palindromic number 99 become 98 then 98/99 98/98 98/97 so on so fourth
OK, you are misunderstanding how nested loops work. Put console.log('j =', j, 'and c =', c);
inside the inner most loop and see. Itâs going to go 99/99, 98/99, 97/99, 96/99 ⌠all the way to 1/99 and only then get to 98/99, 97/99⌠There is no guarantee that the first palindrome number you hit with this method will be the largest.
So, there are two options, switch how you loop the numbers or change your logic of how you evaluate and return the largest palindrome. They are both worth exploring but I will address the latter because it is easiest with your code.
Inside the inner loop you have:
Palind = j * c;
lenC = c.toString().length;
if (Palind === parseFloat(Palind.toString().split("").reverse().join("")) && lenC === n) {
return console.log(Palind);
}
First of all, why are you checking the length of your product? The length of n
requirement refers to the multiplicands, not the product.
In any case, instead of returning the first palindrome you find, you need to see if that is bigger than the biggest palindrome youâve found so far and store it. You donât return the answer until youâve finished all the checks.
A few thoughts on JS conventions:
Usually we donât use Pascal case (camel case with a starting capital) except for classes, constructors, or React components.
Secondly, what are the j
and c
variables named for? Those seem like odd choices. We usually donât use on character names unless it is a common indexing variable (like i
, j
, and then, k
) or if it is a parameter in a short callback function. It should at least be instantly obvious. By convention, I would have gone with i
and j
.
Also, return console.log(Palind)
isnât going to work because afaik âconsole.logâ returns undefined
, not what was passed to it. But this might have been accidentally left over from debugging.
Keep at it. Let us know if you need more help.