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)
相关推荐
小小测试开发5 小时前
安装 Python 3.10+
开发语言·人工智能·python
梦想不只是梦与想5 小时前
Python 中的装饰器
python·装饰器
我叫唧唧波6 小时前
Python+AI 全栈学习笔记
人工智能·python·学习
8Qi86 小时前
LeetCode 235. 二叉搜索树的最近公共祖先(LCA)
算法·leetcode·二叉树·递归·二叉搜索树·lca·迭代
copyer_xyf6 小时前
Python 异常处理
前端·后端·python
麻雀飞吧7 小时前
期货多合约策略目标持仓怎么更新才不乱
python·区块链
Cthy_hy7 小时前
拓扑排序超详解:原理 + Kahn 贪心算法
python·算法·贪心算法
LSssT.7 小时前
【01】Python 机器学习
开发语言·python
为爱停留7 小时前
给智能体装上「刹车」:中断(Interrupts)与人工审批全解析
python
l1t8 小时前
DeepSeek总结的使用实体-组件-系统和基于存在性处理进行Python编程39-40
开发语言·python