Problem 4
A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.
here is my code below. I try my code on the product of two 2-digit numbers, it prints 9009 (correct answer). but for the 3 digit numbers, the correct answer is 906609, my answer is 956459. I don't know what 's wrong with my code, please help. Thanks.
let num;//product of two numbers
let paNum=[];//array for palindrome number
for(i=100;i<1000;i++)
{
for (j=100;j<1000;j++)
{
num = i*j;
str= num.toString();//change the number to a string
if (str.substr(0,1) == str.substr(-1,1) && str.substr(1,1) == str.substr(-2,1))
{
paNum.push(num);
}
else{};
};
};
console.log(paNum);
console.log(Math.max(...paNum));
I got the correct answer with the following modification.
for(i=100;i<1000;i++) {
for (j=100;j<1000;j++){
num = i*j;
str= num.toString();//change the number to a string
let len = str.length - 1;
let checkedDigit = [];
//Iterate the string from 0 to string length/2 and check whether it is a palindrom.
for (k = 0; k < str.length/2; k++) {
if (str.substr(k, 1) === str.substr(len - (len + 1 + k), 1)) {
//If the two corresponding digits are equal, add a true. (Else false)
checkedDigit[k] = true;
} else {
checkedDigit[k] = false;
}
}
function checkDigit(val) {
return val === true;
}
//Check whether all the elements in the checkedDigit array are true.
if (checkedDigit.every(checkDigit)) {
paNum.push(num);
}
};
};
console.log(paNum);
console.log(Math.max(...paNum));
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments