<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:
        if n == '10' or n == '11':
            return '9'
        
        l = len(n)
        if l % 2 == 0:
            half = l // 2
        else:
            half = l // 2 + 1
        
        def makePalindrome(s):
            rev = s[0:l - half][::-1]
            if len(s) < l - half:
                return s + s[-1] + rev
            return s + rev
        
        halfV = int(n[0:half])
        up = str(halfV + 1)
        mid = str(halfV)
        down = str(halfV - 1)

        up_pal = makePalindrome(up)
        mid_pal = makePalindrome(mid)
        down_pal = makePalindrome(down)
    
        diff_up = int(up_pal) - int(n)
        diff_mid = abs(int(mid_pal) - int(n))
        diff_down = int(n) - int(down_pal)

        if diff_mid != 0:
            if diff_mid <= diff_up and diff_mid < diff_down:
                return mid_pal
        if diff_down > diff_up:
            return up_pal
        return down_pal
16400