Skip to content

Commit 3101964

Browse files
committed
Add solution #564
1 parent 6fd0d17 commit 3101964

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -446,6 +446,7 @@
446446
559|[Maximum Depth of N-ary Tree](./0559-maximum-depth-of-n-ary-tree.js)|Easy|
447447
560|[Subarray Sum Equals K](./0560-subarray-sum-equals-k.js)|Medium|
448448
563|[Binary Tree Tilt](./0563-binary-tree-tilt.js)|Easy|
449+
564|[Find the Closest Palindrome](./0564-find-the-closest-palindrome.js)|Hard|
449450
565|[Array Nesting](./0565-array-nesting.js)|Medium|
450451
566|[Reshape the Matrix](./0566-reshape-the-matrix.js)|Easy|
451452
567|[Permutation in String](./0567-permutation-in-string.js)|Medium|
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* 564. Find the Closest Palindrome
3+
* https://leetcode.com/problems/find-the-closest-palindrome/
4+
* Difficulty: Hard
5+
*
6+
* Given a string n representing an integer, return the closest integer (not including itself),
7+
* which is a palindrome. If there is a tie, return the smaller one.
8+
*
9+
* The closest is defined as the absolute difference minimized between two integers.
10+
*/
11+
12+
/**
13+
* @param {string} n
14+
* @return {string}
15+
*/
16+
var nearestPalindromic = function(n) {
17+
const num = BigInt(n);
18+
19+
if (num <= 10n) return String(num - 1n);
20+
if (num === 11n) return '9';
21+
if (n === '1' + '0'.repeat(n.length - 1)) return String(num - 1n);
22+
if (n === '9'.repeat(n.length)) return String(num + 2n);
23+
24+
const leftHalf = n.slice(0, Math.ceil(n.length / 2));
25+
const leftNum = BigInt(leftHalf);
26+
const candidates = [
27+
String(10n ** BigInt(n.length - 1) - 1n),
28+
createPalindrome(leftNum - 1n, n.length),
29+
createPalindrome(leftNum, n.length),
30+
createPalindrome(leftNum + 1n, n.length),
31+
String(10n ** BigInt(n.length) + 1n)
32+
].filter(x => x !== n);
33+
34+
return candidates.reduce((min, curr) => {
35+
const currDiff = BigInt(curr) > num ? BigInt(curr) - num : num - BigInt(curr);
36+
const minDiff = BigInt(min) > num ? BigInt(min) - num : num - BigInt(min);
37+
return currDiff < minDiff
38+
? curr
39+
: currDiff === minDiff
40+
? (curr < min ? curr : min)
41+
: min;
42+
});
43+
44+
function createPalindrome(left, length) {
45+
const s = String(left);
46+
return length % 2 === 0
47+
? s + s.split('').reverse().join('')
48+
: s + s.slice(0, -1).split('').reverse().join('');
49+
}
50+
};

0 commit comments

Comments
 (0)