Skip to content

Latest commit

 

History

History
42 lines (35 loc) · 1.33 KB

File metadata and controls

42 lines (35 loc) · 1.33 KB

564. Find the Closest Palindrome

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 (Python)

1. Solution

class Solution:
    def nearestPalindromic(self, n: str) -> str:
        nums = []
        nums.append(str(int(n[:(len(n) + 1) // 2])))
        nums.append(str(int(n[:(len(n) + 1) // 2]) - 1))
        nums.append(str(int(n[:(len(n) + 1) // 2]) + 1))
        nums[0] += nums[0][:len(n) // 2][::-1]
        nums[1] += nums[1][:len(n) // 2][::-1]
        nums[2] += nums[2][:len(n) // 2][::-1]
        nums.append("9" * max(len(n) - 1, 1))
        nums.sort(key=lambda x: (x == n, abs(int(x) - int(n)), int(x)))

        return nums[0]