Skip to content

Commit 2cda71c

Browse files
authored
Update README.md
1 parent 29212ad commit 2cda71c

File tree

1 file changed

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

1 file changed

+55
-0
lines changed

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

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,61 @@ func abs(x int) int {
189189
}
190190
```
191191

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

194249
<!-- solution:end -->

0 commit comments

Comments
 (0)