Skip to content

Commit b7c22ac

Browse files
authored
feat: add solutions to lc problem: No.0564
1 parent 7e3fcaf commit b7c22ac

File tree

1 file changed

+45
-0
lines changed
  • solution/0500-0599/0564.Find the Closest Palindrome

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* @param {string} n
3+
* @return {string}
4+
*/
5+
6+
function nearestPalindromic(n) {
7+
const x = BigInt(n);
8+
let ans = null;
9+
10+
for (const t of getCandidates(n)) {
11+
if (
12+
ans === null ||
13+
absDiff(t, x) < absDiff(ans, x) ||
14+
(absDiff(t, x) === absDiff(ans, x) && t < ans)
15+
) {
16+
ans = t;
17+
}
18+
}
19+
20+
return ans.toString();
21+
}
22+
23+
function getCandidates(n) {
24+
const length = n.length;
25+
const res = new Set();
26+
27+
res.add(BigInt(Math.pow(10, length - 1) - 1));
28+
res.add(BigInt(Math.pow(10, length) + 1));
29+
30+
const left = BigInt(n.substring(0, Math.ceil(length / 2)));
31+
32+
for (let i = left - 1n; i <= left + 1n; i++) {
33+
const prefix = i.toString();
34+
const t = prefix + prefix.split('').reverse().slice(length % 2).join('');
35+
res.add(BigInt(t));
36+
}
37+
38+
res.delete(BigInt(n));
39+
return res;
40+
}
41+
42+
function absDiff(a, b) {
43+
return a > b ? a - b : b - a;
44+
}
45+

0 commit comments

Comments
 (0)