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