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)
相关推荐
Derrick__19 分钟前
Scrapling 爬取豆瓣电影Top250
开发语言·python·网络爬虫·豆瓣·scrapling
2401_8357925410 分钟前
Java复习上
java·开发语言·python
alphaTao12 分钟前
LeetCode 每日一题 2026/3/23-2026/3/29
服务器·windows·leetcode
Ai财富密码32 分钟前
AI生成大屏可视化:数据智能驱动下的高维洞察与决策中枢
开发语言·人工智能·python·sdd
半兽先生35 分钟前
01阶段:大模型语言入门
开发语言·python
l1t39 分钟前
执行python pyperformance基准测试的步骤
开发语言·python
chushiyunen39 分钟前
python中的for循环、dict、set、列表、数组等
开发语言·python
不光头强43 分钟前
力扣78子集题解
算法·leetcode·深度优先
Magic--1 小时前
经典概率题:飞机座位分配问题(LeetCode 1227)超详细解析
算法·leetcode·职场和发展
sqyno1sky1 小时前
数据分析与科学计算
jvm·数据库·python