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)
相关推荐
skywalk8163几秒前
介绍一下QuantConnect Lean(python 15k star)
开发语言·python·量化
lcz-20004 分钟前
Silero-VAD模型自定义微调
python·音视频·vad·silero
CCPC不拿奖不改名10 分钟前
Git 核心操作命令
人工智能·git·python·rnn·自然语言处理·josn
XerCis11 分钟前
Python包与环境管理工具uv及pyproject.toml指南
开发语言·python·uv
CCPC不拿奖不改名15 分钟前
面向计算机应用的数学
人工智能·python·rnn·深度学习·embedding·应用开发数学
程序员-King.16 分钟前
day150—数组—二叉树的锯齿形层序遍历(LeetCode-103)
算法·leetcode·二叉树
sin_hielo17 分钟前
leetcode 3314(位运算,lowbit)
数据结构·算法·leetcode
Remember_99318 分钟前
【数据结构】深入理解排序算法:从基础原理到高级应用
java·开发语言·数据结构·算法·spring·leetcode·排序算法
bybitq19 分钟前
Leetcode-124-二叉树最大路径和-Python
算法·leetcode·深度优先
山川而川-R20 分钟前
windows系统安装labelimg按“W”键报错
python