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)
相关推荐
Sw1zzle5 小时前
算法入门(四):二叉树 - 递归遍历三件套
算法·leetcode
海石6 小时前
子树怎么找?树的3种遍历方式来帮忙!
算法·leetcode
海石6 小时前
难度分 1588:思路 + 技巧 = AC
算法·leetcode
nothing&nowhere7 小时前
用 Python 做问卷数据清洗:无效样本检测与处理实战
开发语言·python·数据清洗·数据处理·问卷星·问卷星脚本·刷问卷
花酒锄作田7 小时前
如何发布自己的 Python 库到 PyPI
python
researcher-Jiang7 小时前
Design Patterns——Template Method入门到情景实战
python·设计模式·模板方法模式
飞猪~11 小时前
LangChain python 版本 第一集
开发语言·python·langchain
2601_9563198812 小时前
最新AI量化提效,先做可验证的小流程
人工智能·python
开飞机的舒克_13 小时前
FastAPI 实战入门:从路由、参数校验到依赖注入的后端开发指南
python·fastapi