<p>Given a string <code>n</code> representing an integer, return <em>the closest integer (not including itself), which is a palindrome</em>. If there is a tie, return <em><strong>the smaller one</strong></em>.</p>

<p>The closest is defined as the absolute difference minimized between two integers.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> n = &quot;123&quot;
<strong>Output:</strong> &quot;121&quot;
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> n = &quot;1&quot;
<strong>Output:</strong> &quot;0&quot;
<strong>Explanation:</strong> 0 and 2 are the closest palindromes but we return the smallest which is 0.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n.length &lt;= 18</code></li>
	<li><code>n</code> consists of only digits.</li>
	<li><code>n</code> does not have leading zeros.</li>
	<li><code>n</code> is representing an integer in the range <code>[1, 10<sup>18</sup> - 1]</code>.</li>
</ul>

class Solution:
    def nearestPalindromic(self, n: str) -> str:
        def helper(fhalf, iseven):
            resnum = fhalf
            if not iseven:
                fhalf //= 10  # Remove the middle digit if odd length
            while fhalf:
                digit = fhalf % 10
                resnum = resnum * 10 + digit
                fhalf //= 10
            return resnum

        l = len(n)
        mid = l // 2
        fhalf = int(n[:mid + (l % 2)])  # Extract the first half, including the middle digit for odd length
        possible = []

        # Generate palindromes from fhalf, fhalf+1, and fhalf-1
        possible.append(helper(fhalf, l % 2 == 0))
        possible.append(helper(fhalf + 1, l % 2 == 0))
        possible.append(helper(fhalf - 1, l % 2 == 0))

        # Add edge cases for numbers like 999... and 1000...
        possible.append(10**l + 1)
        possible.append(10**(l-1) - 1)

        num = int(n)
        diff = float("inf")
        res = -1

        for p in possible:
            if p != num:  # Skip if the palindrome is the same as the original number
                current_diff = abs(p - num)
                if current_diff < diff or (current_diff == diff and p < res):
                    diff = current_diff
                    res = p

        return str(res)

16600