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)
相关推荐
用户83562907805139 分钟前
使用 Python 在 Excel 中插入 OLE 对象
后端·python
one3121 小时前
高精度MEMS电容式倾角传感器:原理、结构与Python三维可视化
开发语言·python
重生之后端学习1 小时前
53. 最大子数组和[中等]✅
java·数据结构·算法·leetcode·职场和发展
深蓝海拓2 小时前
基于QtPy (PySide6) 的PLC-HMI工程实战记录(七)创建适合HMI项目的数字输入/显示类部件
python
MartinYeung52 小时前
[论文学习]MPIB:医疗提示注入基准——针对LLM临床安全性的系统性评估
人工智能·python·学习
用户8356290780512 小时前
使用 Python 为 PowerPoint 演示文稿添加评论
后端·python
阿图灵3 小时前
OpenCV 绘图五件套:画圆、文本、线段、矩形与椭圆
图像处理·人工智能·python·opencv·计算机视觉·绘图
web行路人3 小时前
AI全栈之旅 · 第一周总结
python
slacker-kian3 小时前
HuggingFace API加载模型超时:用 ModelScopeAPI 替代
人工智能·python·transformer·huggingface·blip·modelscope·blipprocessor