16 lines C++


  • 1
    L

    Here's my short C++ solution. You can refer to the perfect explanation by @awice here. Thanks for attention :-)

    class Solution {
    public:
        string nearestPalindromic(string n) {
            function<long(long, int)> mirror = [&n](long mid, int d) {
                string prefix = to_string(mid + d);
                return stol(prefix + string(prefix.rbegin() + (n.size() % 2), prefix.rend()));
            };
            
            long mid = stol(n.substr(0, (n.size() + 1) / 2));
            set<long> candidates = { pow(10, n.size() - 1) - 1, mirror(mid, -1), mirror(mid, 0), mirror(mid, 1), pow(10, n.size()) + 1 };
    
            long num = stol(n);
            candidates.erase(num);
            return to_string(*min_element(candidates.begin(), candidates.end(), [num](long a, long b) { return abs(num - a) < abs(num - b); }));
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.