leetcode564+找到最近的回文数,改变右半边

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013554860/article/details/82431617

https://leetcode.com/problems/find-the-closest-palindrome/description/

class Solution {
public:
    string nearestPalindromic(string n) {
        long len = n.size(), num = stol(n), res = 0, minDiff = LONG_MAX;
        set<long> St;
        St.insert(pow(10, len) + 1);
        St.insert(pow(10, len-1) - 1);
        long prefix = stol(n.substr(0, (len+1) / 2));
        for(long i = -1; i<=1; i++){
            string pre = to_string(prefix+i);
            string str = pre + string(pre.rbegin()+(len&1), pre.rend());
            St.insert(stol(str));
        }
        St.erase(num);
        for(auto a:St){
            long diff = abs(a-num);
            if(diff < minDiff){
                minDiff = diff;
                res = a;
            }
            else if(diff == minDiff){
                res = min(res, a);
            }
        }
        return to_string(res);
    }
};

猜你喜欢

转载自blog.csdn.net/u013554860/article/details/82431617