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)
相关推荐
小猴子爱上树2 分钟前
跨马翻译:批量图片翻译+视频字幕+智能抠图,跨境电商翻译工具
python·音视频
棉猴15 分钟前
玩游戏学Python2-IDLE与pgzero入门
开发语言·python·游戏·玩游戏·pgzero·pgzrun
INGNIGHT19 分钟前
593 · 石头游戏 II (区间dp石子合并 翻倍循环问题)
leetcode
TechEdu20260621 分钟前
[人工智能]Python12: SciPy 实战指南
人工智能·python·scipy
aqiu11111134 分钟前
【C++算法打怪专栏】LeetCode 402. 移掉 K 位数字(单调栈 + 贪心)
c++·算法·leetcode
jack186891 小时前
Github Copilot 高效开发实战场景指南
python
AIFQuant1 小时前
Python A股实时行情API接入:沪深股票数据与WebSocket推送实战
开发语言·python·websocket·金融·a股行情
小小龙学IT1 小时前
Python Matplotlib 数据可视化库深度解析
python·信息可视化·matplotlib
小小张说故事1 小时前
Python 到底是值传递还是引用传递?一个赋值实验讲透,别再背结论了
python
Maxwin1 小时前
AI 生成的视频怎么局部修改?2026 年分章生成 Manim 代码的最新做法
python·aigc