Reputation: 2368
I'm trying to get the largest palindrome made from the product of two 3-digit numbers. In case you don't know, a palindrome is a number that is the same forwards as it is backward (ex: 9009, or 55855, etc..).
My method involves looping through all three digit numbers and multiplying them, if the product matches itself reversed, updating the variable 'palindrome' with that product. I'm expecting 906609, but it's returning 99999.
Been racking my brain on this one, don't see anything wrong but there's obviously something. Any thoughts?
//Hoist 'palindrome'
var palindrome = 0;
//Loop through 100 - 1000
for(var i = 100; i < 1000; i++) {
//Within that loop, loop through 100 - 1000
for(var k = 100; k < 1000; k++) {
//Convert product of K & I and reverse to strings
var product = (k * i).toString();
var reversed = product.match(/.{1}/g).reverse().toString().replace(/,/g, '');
//If the product and reverse are the same, update palindrome
if(product === reversed) {
if(reversed > palindrome) {
var palindrome = product;
}
}
}
}
//Expecting 906609, but returns 99999
console.log(palindrome)
Upvotes: 0
Views: 50
Reputation: 138267
because
"99999" > "906609" // true
as you are comparing strings, they are compared lexically. You want to compare numbers:
if(+reversed > +palindrome)
Upvotes: 4