寻找最近的回文数

原题:https://leetcode-cn.com/problems/find-the-closest-palindrome/

解题思路是造了几个样例,然后分析分类解决

 

class Solution
{
    long long num(string s)
    {
        long long ans = 0;
        for (auto i : s)
            ans = ans * 10 + i - '0';
        return ans;
    }
    string ch(long long x)
    {
        return to_string(x);
    }
    long long abs(long long x, long long y)
    {
        return x > y ? x - y : y - x;
    }
    long long re(long long x, int id)
    {
        //根据前半字符串转换成回文
        string y = ch(x), z = string(y, 0, id);
        reverse(z.begin(), z.end());
        y += z;
        if (id > z.length())//位数控制
            y += y[0];
        return num(y);
    }
public:
    string nearestPalindromic(string n)
    {
        string x(n, 0, (n.length() + 1) / 2);
        long long u = num(x) - 1, v = num(x), w = num(x) + 1, p = num(n), ans;
        u = re(u, n.length() / 2);
        if (v == 1 && n.length() == 2)//10,11是一处bug,特别处理了
            u = 9;
        v = re(v, n.length() / 2);
        w = re(w, n.length() / 2);
        ans = u;
        if (abs(v, p) < abs(ans, p) && v != p)
            ans = v;
        if (abs(w, p) < abs(ans, p))
            ans = w;
        return ch(ans);
    }
};
solution

 

analyse:

造几组样例

129=131,1191=1221,1800=1771,1091=1111,2000=2002(2112、1991)
    思路是:
        取前半,转换数字-1,0,+1
        对称取后半,逐个比较
        对半考虑奇偶性,(len+1)/2后取len/2位
posted @ 2022-03-02 20:38  Renhr  阅读(10)  评论(0)    收藏  举报