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)
相关推荐
2601_962885723 小时前
如何用 Python 计算 VaR 和 CVaR(在险价值)?
开发语言·python
李航19833 小时前
DeepSeekAI建模三 - 实战建模一组柜子
人工智能·python·计算机视觉·ai·ai编程
Nil2083 小时前
LeetCode 283移动零
数据结构·算法·leetcode
严谨的麻辣烫4 小时前
静态代理 IP 的出口一致性如何验证?Python 请求检测与异常排查
开发语言·python·http·网络安全
我命由我123454 小时前
5-1.Python 编码进阶 - 函数进阶(参数、返回值、递归、函数作为参数传递、lambda 匿名函数)
java·服务器·数据库·后端·python·java-ee·python3.11
FITA阿泽要努力5 小时前
Fork Agent:共享上下文的艺术
开发语言·python·agent
文丑颜不良啊5 小时前
LeetCode226~250题目解析
java·leetcode
DeeGLMath5 小时前
optimtool最新版研究梯度优化
python·optimtool·梯度优化
坐吃山猪5 小时前
Python-Hermite基函数
开发语言·python
空~自由6 小时前
Python 正则 . * ? .* .*? (.*?) 通俗讲解
开发语言·python