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)
相关推荐
木头左9 分钟前
波动率聚类现象对ETF网格密度配置的启示与应对策略
python
华仔AI智能体42 分钟前
Qwen3(通义千问3)、OpenAI GPT-5、DeepSeek 3.2、豆包最新模型(Doubao 4.0)通用模型能力对比
人工智能·python·语言模型·agent·智能体
盼哥PyAI实验室43 分钟前
踏上编程征程,与 Python 共舞
开发语言·python
西柚小萌新1 小时前
【深入浅出PyTorch】--6.2.PyTorch进阶训练技巧2
人工智能·pytorch·python
weixin_307779131 小时前
使用Python高效读取ZIP压缩文件中的UTF-8 JSON数据到Pandas和PySpark DataFrame
开发语言·python·算法·自动化·json
哎呀呦呵1 小时前
python内置模块-re模块介绍使用
java·python·mysql
paoqi 包奇2 小时前
pycharm中使用anaconda指定虚拟环境
ide·python·pycharm
fsnine2 小时前
图像视觉——颜色识别
图像处理·python·计算机视觉
小张的博客之旅2 小时前
2025年“羊城杯”网络安全大赛 线上初赛 (WriteUp)
python·学习·网络安全