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)
相关推荐
艾斯特_10 分钟前
从模型调用到可用聊天应用:会话状态与消息协议
python·ai·aigc
alphaTao14 分钟前
LeetCode 每日一题 2026/7/20-2026/7/26
算法·leetcode
Marst Code20 分钟前
Python 3.9 已停止维护!从 3.9 到 3.14 全版本深度对比,生产环境该选哪个?
开发语言·python
llwszx28 分钟前
【Java/Go后端手撸原生Agent(第九篇):Plan-and-Execute规划模式——从“走一步看一步“到“先谋后动“】
java·python·golang·agent开发·plan模式·规划执行模式
lxw184491251439 分钟前
Python uv 完整使用教程
python·conda·pip·uv
hangyuekejiGEO1 小时前
临沂GEO技术解析与行业应用方案
人工智能·python
圣保罗的大教堂1 小时前
leetcode 3514. 不同 XOR 三元组的数目 II 中等
leetcode
不做Java程序猿好多年2 小时前
Java中 String、StringBuffer、StringBuilder 的区别详解
开发语言·python
金銀銅鐵2 小时前
[Python] 用 turtle 来绘制国际象棋棋盘(不含棋子)
python·游戏
這花開嗎2 小时前
2026年TTS文字转语音API哪家强?批量自动化配音成本与技术实测
python·flask·自动化