Last active
November 9, 2021 17:14
-
-
Save gauthierm/a336a9fd0615f68c2d3786f6f65802d0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getDigitAt(position, value) { | |
return Math.floor((value % 10 ** position) / 10 ** (position - 1)); | |
} | |
function getLength(value) { | |
return Math.floor(Math.log10(value)) + 1; | |
} | |
function isPalindrome(value) { | |
const digits = getLength(value); | |
const halfDigits = Math.floor(digits / 2); | |
for (let i = 0; i < halfDigits; i++) { | |
if (getDigitAt(i + 1, value) !== getDigitAt(digits - i, value)) { | |
return false; | |
} | |
} | |
return true; | |
} | |
function getLargestPalindrome(digits1, digits2) { | |
const max1 = 10 ** digits1 - 1; | |
const max2 = 10 ** digits2 - 1; | |
const min1 = 10 ** (digits1 - 1) - 1; | |
const min2 = 10 ** (digits2 - 1) - 1; | |
let largest = 0; | |
for (let i = max1; i > min1; i--) { | |
for (let j = max2; j > min2; j--) { | |
const sum = i * j; | |
if (sum > largest && isPalindrome(sum)) { | |
largest = sum; | |
} | |
} | |
} | |
return largest; | |
} | |
getLargestPalindrome(3, 3); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment