Skip to content

Commit 7e3fcaf

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

File tree

1 file changed

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

1 file changed

+49
-0
lines changed

solution/0500-0599/0564.Find the Closest Palindrome/README_EN.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,55 @@ func abs(x int) int {
187187
}
188188
```
189189

190+
#### JavaScript
191+
```js
192+
/**
193+
* @param {string} n
194+
* @return {string}
195+
*/
196+
197+
function nearestPalindromic(n) {
198+
const x = BigInt(n);
199+
let ans = null;
200+
201+
for (const t of getCandidates(n)) {
202+
if (
203+
ans === null ||
204+
absDiff(t, x) < absDiff(ans, x) ||
205+
(absDiff(t, x) === absDiff(ans, x) && t < ans)
206+
) {
207+
ans = t;
208+
}
209+
}
210+
211+
return ans.toString();
212+
}
213+
214+
function getCandidates(n) {
215+
const length = n.length;
216+
const res = new Set();
217+
218+
res.add(BigInt(Math.pow(10, length - 1) - 1));
219+
res.add(BigInt(Math.pow(10, length) + 1));
220+
221+
const left = BigInt(n.substring(0, Math.ceil(length / 2)));
222+
223+
for (let i = left - 1n; i <= left + 1n; i++) {
224+
const prefix = i.toString();
225+
const t = prefix + prefix.split('').reverse().slice(length % 2).join('');
226+
res.add(BigInt(t));
227+
}
228+
229+
res.delete(BigInt(n));
230+
return res;
231+
}
232+
233+
function absDiff(a, b) {
234+
return a > b ? a - b : b - a;
235+
}
236+
237+
```
238+
190239
<!-- tabs:end -->
191240

192241
<!-- solution:end -->

0 commit comments

Comments
 (0)