Posted on

Description

Submission

class Solution {
public:
    string nearestPalindromic(string n) {
        long long num = stoll(n);
        int len = n.length();
        int leftLen = (len + 1) / 2;
        if(len == 1) return to_string(stoll(n) - 1);

        string ret = string(len - 1, '9');
        string cur = "1" + string(len - 1, '0') + "1";
        if(ret == n || abs(stoll(cur) - num) < abs(stoll(ret) - num)) ret = cur;
        for(int i = -1; i <= 1; ++i) {
            string left = to_string(stoll(n.substr(0, leftLen)) + i);
            string right = left.substr(0, leftLen - (len&1));
            reverse(right.begin(), right.end());
            cur = left + right;
            if(cur == n) continue;
            if(ret.empty() || abs(stoll(cur) - num) < abs(stoll(ret) - num)) ret = cur;
        }

        return ret;
    }
};


// 127

// 121
// 131. 3 / 2 =1
// 1222. 4 / 2 = 2

Leave a Reply

Your email address will not be published. Required fields are marked *