Python | Leetcode Python题解之第564题寻找最近的回文数

题目:

题解:

python 复制代码
class Solution:
    def nearestPalindromic(self, n: str) -> str:
        m = len(n)
        candidates = [10 ** (m - 1) - 1, 10 ** m + 1]
        selfPrefix = int(n[:(m + 1) // 2])
        for x in range(selfPrefix - 1, selfPrefix + 2):
            y = x if m % 2 == 0 else x // 10
            while y:
                x = x * 10 + y % 10
                y //= 10
            candidates.append(x)

        ans = -1
        selfNumber = int(n)
        for candidate in candidates:
            if candidate != selfNumber:
                if ans == -1 or \
                        abs(candidate - selfNumber) < abs(ans - selfNumber) or \
                        abs(candidate - selfNumber) == abs(ans - selfNumber) and candidate < ans:
                    ans = candidate
        return str(ans)
相关推荐
LeocenaY9 小时前
搜集的一些测开面试题
开发语言·python
嗝o゚9 小时前
昇腾CANN ge 仓的图优化 Pass:哪些 Pass 真正影响推理性能
pytorch·python·深度学习·cann·ge-pass
深度先生10 小时前
Conda 全面讲解——数据科学家的标配工具
python
深度先生10 小时前
虚拟环境:别让包打架
python
漠效11 小时前
随机代理‌IP访问脚本
开发语言·python
SilentSamsara11 小时前
元类与 __init_subclass__:类是如何被“创建“出来的
开发语言·python·青少年编程
隔壁大炮11 小时前
MNE-Python 第6天学习笔记:分段(Epoching)与基线校正
python·eeg·mne·脑电数据处理
珊瑚里的鱼11 小时前
leetcode42雨水
算法·leetcode
SilentSamsara11 小时前
concurrent.futures 实战:进程池与线程池的统一抽象
运维·开发语言·python·青少年编程
水木流年追梦12 小时前
大模型入门-大模型的推理策略
开发语言·python·算法·正则表达式·prompt