<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:
    int digit(int n){
        int ans=0;
        while(n){
            ans++;
            n=n/10;
        }
        return ans;
    }

    string nearestPalindromic(string s) {
        if(s== "10000000000000000")return "9999999999999999";
        int len =s.length();
        long sval  =stol(s);
        vector<long>cand;
        long cand1 = pow(10,len)+1;
        long cand2 = pow(10, len-1)-1;
        cand.push_back(cand1);
        cand.push_back(cand2);

        int mid= (len+1)/2;

        long halfno = stol(s.substr(0,mid));

        vector<string>temp = {to_string(halfno-1), to_string(halfno), to_string(halfno+1)};

        for(auto half: temp){
            string secondhalf = half;
            if(len%2)secondhalf.pop_back();
            reverse(secondhalf.begin(), secondhalf.end());
            cand.push_back(stol(half+secondhalf));
        }
        int diff = INT_MAX;
        long ans= 10000000;
        for(auto no: cand){
            if(no != sval && abs(no-sval) <diff){
                diff = abs(no-sval);
                ans = no;
            }else if(abs(no-sval) ==diff){
                ans = min(ans,no);
            }
        }
        return to_string(ans);
    }
};
9200