-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path564. Find the Closest Palindrome
86 lines (62 loc) · 2.63 KB
/
564. Find the Closest Palindrome
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
Hard
Topics
Companies
Hint
Given a string n representing an integer, return the closest integer (not including itself), which is a palindrome. If there is a tie, return the smaller one.
The closest is defined as the absolute difference minimized between two integers.
Example 1:
Input: n = "123"
Output: "121"
Example 2:
Input: n = "1"
Output: "0"
Explanation: 0 and 2 are the closest palindromes but we return the smallest which is 0.
Constraints:
1 <= n.length <= 18
n consists of only digits.
n does not have leading zeros.
n is representing an integer in the range [1, 1018 - 1].
solution:
package org.example;
public class _Find_the_Closest_Palindrome {
static class Solution {
public String nearestPalindromic(String numberStr) {
long number = Long.parseLong(numberStr);
if (number <= 10) return String.valueOf(number - 1);
if (number == 11) return "9";
int length = numberStr.length();
long leftHalf = Long.parseLong(numberStr.substring(0, (length + 1) / 2));
long[] palindromeCandidates = new long[5];
palindromeCandidates[0] = generatePalindromeFromLeft(leftHalf - 1, length % 2 == 0);
palindromeCandidates[1] = generatePalindromeFromLeft(leftHalf, length % 2 == 0);
palindromeCandidates[2] = generatePalindromeFromLeft(leftHalf + 1, length % 2 == 0);
palindromeCandidates[3] = (long)Math.pow(10, length - 1) - 1;
palindromeCandidates[4] = (long)Math.pow(10, length) + 1;
long nearestPalindrome = 0;
long minDifference = Long.MAX_VALUE;
for (long candidate : palindromeCandidates) {
if (candidate == number) continue;
long difference = Math.abs(candidate - number);
if (difference < minDifference || (difference == minDifference && candidate < nearestPalindrome)) {
minDifference = difference;
nearestPalindrome = candidate;
}
}
return String.valueOf(nearestPalindrome);
}
private long generatePalindromeFromLeft(long leftHalf, boolean isEvenLength) {
long palindrome = leftHalf;
if (!isEvenLength) leftHalf /= 10;
while (leftHalf > 0) {
palindrome = palindrome * 10 + leftHalf % 10;
leftHalf /= 10;
}
return palindrome;
}
}
public static void main(String[] args) {
String numberStr = "123";
Solution s = new Solution();
System.out.println(s.nearestPalindromic(numberStr));
}
}