564. Find the Closest Palindrome

来源:互联网 发布:javascript长度函数 编辑:程序博客网 时间:2024/06/10 09:42

564. Find the Closest Palindrome

Given an integer n, find the closest integer (not including itself), which is a palindrome.

The ‘closest’ is defined as absolute difference minimized between two integers.

Example 1:
Input: “123”
Output: “121”

题目大意:
找到最接近n 的回文数

思路:
假如原来的数是a1a2a3a4a5….an,最接近的n的回文数出现在将a1…an对折即a1…a(n/2)的并在之后复制一遍的回文数,当然最后一位随着是否比原数大或小会有一个抖动,因此要搜索-1,0,+1三种情况
此外比如出现99或者100的情况,我们还需要找pow(10, l) + 1(10…..01)和 pow(10, l - 1) - 1(9……9),我们只需要在这5个数中找就可以了

class Solution {public:    string nearestPalindromic(string n) {        int l = n.size();        set<long> candidates;        // biggest, one more digit, 10...01        candidates.insert(long(pow(10, l)) + 1);        // smallest, one less digit, 9...9 or 0        candidates.insert(long(pow(10, l - 1)) - 1);        // the closest must be in middle digit +1, 0, -1, then flip left to right        long prefix = stol(n.substr(0, (l + 1) / 2));        for(int i=-1;i<=1;i++){            string p = to_string(prefix+i);            string pp = p + string(p.rbegin()+(1&l),p.rend());            cout <<"pp is "<<pp<<endl;            candidates.insert(stol(pp));        }        candidates.erase(stol(n));        long minGap = LONG_MAX;        string minVar ="";        for(auto num : candidates){            long gap = abs(num-stol(n));            if(gap < minGap) {                minGap = gap;                minVar = to_string(num);            }        }        return minVar;    }};