Problem
Given an integer n, find the closest integer (not including itself), which is a palindrome.
The 'closest' is defined as absolute difference minimized between two integers.
Example 1:
Input: "123"
Output: "121"
Note:
The input n is a positive integer represented by string, whose length will not exceed 18.
If there is a tie, return the smaller one as answer.
这tm就是道逻辑题 然后用很多testcase去refactor
Solution
class Solution {
public String nearestPalindromic(String n) {
char[] arr = n.toCharArray();
int i = 0, j = arr.length-1;
while (i < j) arr[j--] = arr[i++];
String curP = String.valueOf(arr);
String preP = nearestPalindrom(curP, -1);
String nextP = nearestPalindrom(curP, 1);
long num = Long.valueOf(n);
long cur = Long.valueOf(curP);
long pre = Long.valueOf(preP);
long next = Long.valueOf(nextP);
long d1 = Math.abs(num - pre);
long d2 = Math.abs(num - cur);
long d3 = Math.abs(num - next);
if (num == cur) {
return d1 <= d3 ? preP : nextP;
} else if (num > cur) {
return d2 <= d3 ? curP : nextP;
} else {
return d1 <= d2 ? preP : curP;
}
}
private String nearestPalindrom(String str, int offset) {
int l1 = str.length()/2, l2 = str.length()-l1;
int half = Integer.valueOf(str.substring(0, l2));
half += offset;
if (half == 0)
//l1 == 0: 1 -> 0 l1 == 1: 10 -> 9
return l1 == 0 ? "0" : "9";
StringBuilder left = new StringBuilder(String.valueOf(half));
StringBuilder right = new StringBuilder(left).reverse();
//1000, l1 = 2, left = 9, so right appends "9"
if (l1 > left.length()) right.append("9");
//for 999, half is 99, when offset = 1, left could be 100, right could be 001
//so when appending to left, right should only take right.substring(2)
//in which 2 is from: right.length()-l1
if (right.length() > l1) left.append(right.substring(right.length()-l1));
else left.append(right);
return left.toString();
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。