LeetCode 0564. Find the Closest Palindrome Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0564. Find the Closest Palindrome

Description

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].

Solutions

Solution 1

PythonJavaC++GoJavaScript
class Solution: def nearestPalindromic(self, n: str) -> str: x = int(n) l = len(n) res = {10 ** (l - 1) - 1, 10**l + 1} left = int(n[: (l + 1) >> 1]) for i in range(left - 1, left + 2): j = i if l % 2 == 0 else i // 10 while j: i = i * 10 + j % 10 j //= 10 res.add(i) res.discard(x) ans = -1 for t in res: if ( ans == -1 or abs(t - x) < abs(ans - x) or (abs(t - x) == abs(ans - x) and t < ans) ): ans = t return str(ans)(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !