<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 {
public:
    string nearestPalindromic(string n) {
        
        int len = n.size();
        long long num = std::stoll(n);
        long long a = previousPalindrome(num);
        long long b = nextPalindrome(num);
        if(std::abs(a - num) <= std::abs(b - num)) {
            return std::to_string(a);
        }
        return std::to_string(b);
    }

    long long convert(long long & num) {

        std::string str = std::to_string(num);
        int n = str.length();
        int left = (n - 1) / 2, right = n / 2;
        while(left >= 0) {
            str[right++] = str[left--];
        }

        return std::stoll(str);
    }

    long long previousPalindrome(long long num) {

        long long left = 0, right = num;
        long long ans = INT_MIN;
        while(left <= right) {
            
            long long mid = (right - left) / 2 + left;
            long long palin = convert(mid);
            if(palin < num) {
                ans = palin;
                left = mid + 1; 
            } else {
                right = mid - 1;
            }
        }

        return ans;
    }

    long long nextPalindrome(long long num) {

        long long left = num, right = 1e18;
        long long ans = INT_MIN;
        while(left <= right) {

            long long mid = (right - left) / 2 + left;
            long long palin = convert(mid);
            if(palin > num) {
                ans = palin;
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return ans;
    }
     

};
11100