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)
相关推荐
文丑颜不良啊7 小时前
LeetCode1941~1960题目解析
java·leetcode
❁满城风絮*7 小时前
Claude Code 学习总结
python·agent·claude
维克兜率天10 小时前
【维克】复合型CTA:趋势+套利的双轮驱动
python·学习方法
伞伞悦读10 小时前
【第76期】两张3行表左连接变5行:主键、validate与未匹配排查完整教程
人工智能·python
用户83562907805111 小时前
使用 Python 在 Excel 中添加和自定义迷你图
后端·python
用户83562907805111 小时前
使用 Python 在 Excel 图表中添加趋势线与回归方程
后端·python
特立独行的猫A11 小时前
一份 Markdown 发十个平台:cspub 一稿多投
java·后端·python
深蓝AI11 小时前
HTTPX 超时 1 秒,接口为何还能跑 2.4 秒?
python
CyrusYiVPP11 小时前
哪个用户会再来买?RFM模型+plotly画出用户分层,数据分析实战第2期
人工智能·python
文丑颜不良啊12 小时前
LeetCode1961~1980题目解析
java·leetcode