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)
相关推荐
L_cl3 分钟前
大模型应用开发 9.FastAPI ① 请求与响应
python·fastapi
洛水水9 分钟前
【力扣100题】58.轮转数组
算法·leetcode
风筝在晴天搁浅24 分钟前
阿里 LeetCode 876.链表的中间节点
算法·leetcode·链表
玖釉-32 分钟前
二叉树展开为链表:从先序遍历到原地指针重排
c++·windows·算法·leetcode·链表
treesforest1 小时前
机房IP是什么?有什么危害?如何识别?
网络·数据库·python·网络协议·tcp/ip·网络安全
洛水水1 小时前
【力扣100题】52.最小路径和
算法·leetcode
圣保罗的大教堂1 小时前
leetcode 3043. 最长公共前缀的长度 中等
leetcode
咕白m6251 小时前
Excel 工作表名称读取(Python 实现)
后端·python
godspeed_lucip2 小时前
LLM和Agent——专题5: LLM Ops 入门(1)
人工智能·python
l1t2 小时前
DeepSeek总结的使用实体-组件-系统和基于存在性处理进行Python编程7-8
开发语言·python