<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.length();

        if(n == "10000000000000000")return "9999999999999999";

        set<string> st;
        if(n == "1")return "0";

        string prefix = n.substr(0 , (len + 1)/2);

        for(auto it : {-1 , 0 , 1}){
            string n_prefix = to_string(stoll(prefix) + it);
            string candidate;
            string temp = n_prefix;
            reverse(temp.begin() , temp.end());

            if(len%2){
                candidate = n_prefix + temp.substr(1);
            }else{
                candidate = n_prefix + temp; 
            }

            st.insert(candidate);
        }

        st.insert(to_string(pow(10 , len) + 1));
        st.insert(to_string(pow(10 , len-1) - 1));

        st.erase(n);

        string close;
        long long minDif = LLONG_MAX;
        long long num  = stoll(n);

        for(auto it : st){
            long long candidateNum = stoll(it);
            long long difference = abs(candidateNum - num);

            if(difference < minDif or difference == minDif and candidateNum < stoll(close)){
                minDif = difference;
                close = to_string(candidateNum);
            }
        }

        return close;
    }
};
10000