Skip to content

Instantly share code, notes, and snippets.

@imolorhe
Created March 6, 2020 02:29
Show Gist options
  • Save imolorhe/a56ebf583436a66b205df3587deb9468 to your computer and use it in GitHub Desktop.
Save imolorhe/a56ebf583436a66b205df3587deb9468 to your computer and use it in GitHub Desktop.
/**
* @param {string} n
* @return {string}
*/
var nearestPalindromic = function(n) {
const nN = BigInt(n);
if (n == 11n) {
return "9";
}
const palindrome = getUniquePalindrome(n);
if (palindrome <= 0) {
return palindrome.toString();
}
const nPalindrome = BigInt(palindrome);
const res = [ palindrome ];
const cnt = (n + '').length;
for (let i = 0; i < cnt; i++) {
res.push(getPalindrome(nN + BigInt(Math.pow(10, i))));
res.push(getPalindrome(nN - BigInt(Math.pow(10, i))));
}
// console.log(res);
return res.reduce((acc, cur) =>
cur != n &&
(
Math.abs(Number(cur - nN)) < Math.abs(Number(acc - nN)) ||
(cur < acc && Math.abs(Number(cur - nN)) == Math.abs(Number(acc - nN)))
) ? cur : acc, 0n).toString();
};
const getPalindrome = n => {
const digits = ('' + n).split('');
for(let i = 0, len = digits.length, mid = (len / 2); i < mid; i++) {
digits[len-i-1] = digits[i];
}
return BigInt(digits.join(''));
};
const getUniquePalindrome = n => {
let result = getPalindrome(n);
if (result != n) {
return result;
}
// console.log(result, n, result[Math.ceil(result.length / 2) - 1]);
result = ('' + result).split('');
if (result[Math.ceil(result.length / 2) - 1] > 1) {
result[Math.ceil(result.length / 2) - 1] = Number(result[Math.ceil(result.length / 2) - 1]) - 1;
} else {
result[Math.ceil(result.length / 2) - 1] = Number(result[Math.ceil(result.length / 2) - 1]) + 1;
}
console.log(result);
return getPalindrome(result.join(''));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment