<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>

#include <algorithm>
#include <climits>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Solution {
public:
    long solve(string half, int n, int bit) {
        long x = stol(half); // Use stol for long type
        x = x + bit;
        string temp = to_string(x);
        string y = temp;
        if (n % 2 == 0) {
            reverse(y.begin(), y.end());
            temp += y;
        } else {
            y.pop_back();
            reverse(y.begin(), y.end());
            temp += y;
        }
        cout<<stol(temp)<<endl;
        return stol(temp);
    }

    string nearestPalindromic(string n) {
        int x = n.size();
        string half;
        if (x % 2 == 0)
            half = n.substr(0, x / 2);
        else
            half = n.substr(0, (x / 2) + 1);

        vector<long> trial;

        trial.push_back(solve(half, x, 0));
        trial.push_back(solve(half, x, 1));
        trial.push_back(solve(half, x, -1));

        // Generating palindromic boundaries
        trial.push_back((long)pow(10, n.size() - 1) - 1);
        trial.push_back((long)pow(10, n.size()) + 1);

        long mini = LONG_MAX; // Use LONG_MAX for long type
        long ans = -1;        // Initialize ans properly

        for (long t : trial) {
            if (stol(n) == t)
                continue;
            if (abs(stol(n) - t) < mini) {
                mini = abs(stol(n) - t);
                ans = t;
            } else if (abs(stol(n) - t) == mini) {
                ans = min(ans, t);
            }
        }
        return to_string(ans);
    }
};

9900