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)
相关推荐
嗯嗯=6 小时前
python学习篇
开发语言·python·学习
WoY20206 小时前
opencv-python在ubuntu系统中缺少依赖
python·opencv·ubuntu
大游小游之老游8 小时前
Python中如何实现一个程序运行时,调用另一文件中的函数
python
mantch8 小时前
个人 LLM 接口服务项目:一个简洁的 AI 入口
人工智能·python·llm
Swift社区8 小时前
LeetCode 465 最优账单平衡
算法·leetcode·职场和发展
weixin_445054729 小时前
力扣热题51
c++·python·算法·leetcode
朱朱没烦恼yeye9 小时前
java基础学习
java·python·学习
databook9 小时前
数据可视化五大黄金原则:让你的图表“会说话”
python·数据分析·数据可视化
ai_top_trends9 小时前
2026 年度工作计划 PPT 模板与 AI 生成方法详解
人工智能·python·powerpoint
智航GIS10 小时前
9.4 Word 自动化
python·自动化·word