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)
相关推荐
三十岁老牛再出发14 分钟前
08.18每日总结
c++·python·numpy·pandas
️学习的小王27 分钟前
Anaconda国内镜像配置与conda常用命令
ide·经验分享·python·conda
Zane199431 分钟前
daemon 线程说没就没?一文讲透 threading 的适用场景与线程安全
后端·python
up up day35 分钟前
Python enchant 模块使用教程
python
zoujiahui_201836 分钟前
Python 包与环境管理工具 uv
开发语言·python·uv
speop1 小时前
llm-algo-leetcode |Task01
算法·leetcode·职场和发展
程序猿阿森1 小时前
Python 闭包与装饰器:从入门到精通
开发语言·python·面试
老大白菜1 小时前
Qwen3.8-27B 本地推理 + DeepSeek Harness 配置
python·qwen·deepseek·harness
Code额2 小时前
Python 连接 DeepSeek API,OpenAI 对话方式总结
后端·python·ai·ai编程
电化学仪器白超2 小时前
MV-CS200-10UC相机参数配置
python·单片机·嵌入式硬件·数码相机·自动化·ltspice