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)
相关推荐
Nil20834 分钟前
leetcode 146LRU缓存
算法·leetcode·缓存
qq_5137280437 分钟前
Alert 原生弹窗处理
python
李可以量化39 分钟前
Redis 从了解到精通(三)上:量化交易场景下的数据备份与安全配置
redis·python·安全·qmt·ptrade
卷无止境43 分钟前
FastAPI查询参数模型:把散落的参数收拢成一个整齐的盒子
后端·python
Code额1 小时前
Python asyncio 异步编程全套学习文档(零基础完整版)
python·学习·oracle·async·异步·asyncio
钱栈up1 小时前
Mac 开发机一键发版不用切环境:我这样改造了团队的后端部署脚本
运维·python·mac
coder_Eight2 小时前
从 3 天到 8 分钟:我如何把垂直科普内容做成了自动化流水线
python·ai编程
水獭比特2 小时前
MCP SDK v2 迁移别只改依赖:先把 FastMCP 3/4 拆成两条测试线
人工智能·python
rannn_1112 小时前
【力扣hot100】图论专题+模板|DFS、BFS、拓扑排序...
java·算法·leetcode·深度优先·图论