[Leetcode] 564. Find the Closest Palindrome 解题报告

本博客介绍了LeetCode 564题目的解法,探讨了如何找到一个整数的最近回文数。通过分析,确定了三种可能的情况:1) 多一位的回文数,2) 少一位的回文数,3) 与原数位数相同且后半部分为前半部分翻转的数。并详细解释了这三种情况的示例,最后给出了实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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"

Note:

  1. The input n is a positive integer represented by string, whose length will not exceed 18.
  2. If there is a tie, return the smaller one as answer.

思路

和n最接近的回文数根据位数划分,则只有3种可能:

1:比n多1位的数,例如对于99而言,距离它最近的回文数就是101;

2:比n少1位的数,例如对于101, 距离它最近的回文数就是99;

3:和n位数一样,并且其后一半是n的前一半的翻转的数。这样的数又可以分为3种:1)中间数和n相同的,例如123的最近回文数就是121;2)中间数比n大1,例如189的最近回文数就是191;3)中间数比n小1,例如920的最近回文数就是919。

所以只要把这5个数分别计算出来,然后比较哪一个和n最接近即可。

代码

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 ( long i = -1; i <= 1; ++i ) {
            string p = to_string(prefix + i);
            string pp = p + string(p.rbegin() + (l & 1), p.rend());
            candidates.insert(stol(pp));
        }
        long num = stol(n), minDiff = LONG_MAX, diff, minVal;
        candidates.erase(num);                  // cannot be itself
        for ( long val : candidates ) {
            diff = abs(val - num);
            if ( diff < minDiff ) {
                minDiff = diff;
                minVal = val;
            }
        }
        return to_string(minVal);
    }
};
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值