File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
solution/0500-0599/0564.Find the Closest Palindrome Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
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
+
You can’t perform that action at this time.
0 commit comments