File tree Expand file tree Collapse file tree 1 file changed +42
-1
lines changed
src/main/java/com/fishercoder/solutions Expand file tree Collapse file tree 1 file changed +42
-1
lines changed Original file line number Diff line number Diff line change 21
21
public class _564 {
22
22
23
23
public String nearestPalindromic (String n ) {
24
- return "" ;
24
+ if (n .length () >= 2 && allNine (n )) {
25
+ String s = "1" ;
26
+ for (int i = 0 ; i < n .length () - 1 ; i ++) {
27
+ s += "0" ;
28
+ }
29
+ s += "1" ;
30
+ return s ;
31
+ }
32
+ boolean isOdd = (n .length () % 2 != 0 );
33
+ String left = n .substring (0 , (n .length () + 1 ) / 2 );
34
+ long [] increment = {-1 , 0 , +1 };
35
+ String ret = n ;
36
+ long minDiff = Long .MAX_VALUE ;
37
+ for (long i : increment ) {
38
+ String s = getPalindrom (Long .toString (Long .parseLong (left ) + i ), isOdd );
39
+ if (n .length () >= 2 && (s .length () != n .length () || Long .parseLong (s ) == 0 )) {
40
+ s = "" ;
41
+ for (int j = 0 ; j < n .length () - 1 ; j ++) {
42
+ s += "9" ;
43
+ }
44
+ }
45
+ long diff = s .equals (n ) ? Long .MAX_VALUE : Math .abs (Long .parseLong (s ) - Long .parseLong (n ));
46
+ if (diff < minDiff ) {
47
+ minDiff = diff ;
48
+ ret = s ;
49
+ }
50
+ }
51
+ return ret ;
52
+ }
53
+
54
+ private String getPalindrom (String s , boolean isOdd ) {
55
+ String right = new StringBuilder (s ).reverse ().toString ();
56
+ return isOdd ? s .substring (0 , s .length () - 1 ) + right : s + right ;
57
+ }
58
+
59
+ private boolean allNine (String s ) {
60
+ for (int i = 0 ; i < s .length (); i ++) {
61
+ if (s .charAt (i ) != '9' ) {
62
+ return false ;
63
+ }
64
+ }
65
+ return true ;
25
66
}
26
67
27
68
}
You can’t perform that action at this time.
0 commit comments