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)
相关推荐
bill32822780431 小时前
从 0 到 1 掌握 1688API:商品详情获取技巧
python
hboot8 小时前
AI工程师第五课 - 大语言模型基础
python·llm·fastapi
AOwhisky9 小时前
Python 学习笔记(第一期与第二期)——基础语法——核心知识点自测与详解
开发语言·笔记·python·学习·云原生·运维开发
STLearner10 小时前
ICML 2026 | LLM×Graph论文总结[1]【图基础模型,文本属性图,多模态属性图,图对齐,图提示学习,关系深度学习
论文阅读·人工智能·python·深度学习·学习·机器学习·数据挖掘
习明然11 小时前
我的本地化AI项目(三)
人工智能·python·electron·c#·avalonia
什巳11 小时前
JAVA练习278- 和为 K 的子数组
java·学习·算法·leetcode
喜欢的名字被抢了11 小时前
Python实战:SQLAlchemy ORM与FastAPI项目集成
开发语言·python·sql·教程·fastapi
夏季疯13 小时前
读论文:STARS 是什么结构?一个统一的歌声自动标注框架
python
鱼儿也有烦恼14 小时前
快速学完 LeetCode top 1~50
leetcode·algorithm
光测实验室14 小时前
3种Python降噪算法实测:我把处理速度提升了20倍
python