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)
相关推荐
小田学Python5 小时前
100行Python代码,搭一个能干活的AI Agent
python·langchain·大模型·ai agent
Csvn6 小时前
🐍 Day3 : Python 容器精讲 — list、dict、set、tuple 底层实现与高级操作
后端·python
weixin-a153003083166 小时前
python-装饰器
开发语言·python
我的xiaodoujiao7 小时前
快速学习Python基础知识详细图文教程17--类型注解和断点调试
开发语言·python·学习·测试工具
.道阻且长.7 小时前
5.LeetCode算法习题讲解--双指针--有效三角形的个数
算法·leetcode·职场和发展
每天吃饭的羊8 小时前
Chrome DevTools MCP
python
水獭比特10 小时前
localhost 不是安全边界:给 Agent Web 入口补上四层门禁
人工智能·python
Generalzy10 小时前
Whisper + VAD + TTS:一套完整的 Python 本地语音处理流水线
python·whisper·语音识别
qpsj10 小时前
让 LLM 控制 AutoCAD/ZWCAD:COM 自动化 + MCP 封装
python·llm
赟爸10 小时前
直播切片素材杂乱不好复用,易元AI要怎么处理
大数据·人工智能·python