File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed
solution/0500-0599/0564.Find the Closest Palindrome Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change @@ -189,6 +189,61 @@ func abs(x int) int {
189
189
}
190
190
```
191
191
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
+
192
247
<!-- tabs:end -->
193
248
194
249
<!-- solution:end -->
You can’t perform that action at this time.
0 commit comments