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)
相关推荐
开开心心就好7 小时前
Word双击预览图片插件弥补Word功能缺失
人工智能·python·智能手机·ocr·电脑·word·音视频
qq_263_tohua8 小时前
第113期 20260725 最近在阅读叶沅鑫老师的多模态配准书籍,发现有不少错误,让人读了头脑发大。
python
可触的未来,发芽的智生8 小时前
发现-元认知技能,激起神经符号系统跃变
javascript·人工智能·python·程序人生·自然语言处理
第二个人8 小时前
Python Web开发:从Flask到FastAPI,我经历了什么
前端·python·flask
蓝创工坊Blue Foundry9 小时前
扫描件批量转 Excel:先确认要整表还原还是字段汇总
python·pdf·ocr·excel
二十雨辰9 小时前
[爬虫]-解析
开发语言·python
天天爱吃肉821810 小时前
AI Agent时代你的经验值多少钱?
人工智能·python·功能测试·学习·汽车
鱼香鱼香rose10 小时前
java-2
java·开发语言·python
tkevinjd18 小时前
MiniCode 项目详解6:原项目控制系统的10个缺陷(已修复)
python·llm·agent
dNGUZ7UGj20 小时前
10分钟完成第一个Python小游戏
python·django