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 分钟前
LeetCode 热题 100 之 279. 完全平方数 322. 零钱兑换 139. 单词拆分 300. 最长递增子序列
java·算法·leetcode·职场和发展
MoRanzhi120330 分钟前
Pillow 图像算术运算与通道计算
图像处理·人工智能·python·计算机视觉·pillow·图像差异检测·图像算术运算
滴滴答滴答答44 分钟前
机考刷题之 12 LeetCode 684 冗余的边
算法·leetcode·职场和发展
codeyanwu1 小时前
LeetCode Hot 100 -- 图论
leetcode·深度优先·图论
怪侠_岭南一只猿1 小时前
爬虫阶段三实战练习题二:使用 Selenium 模拟爬取拉勾网职位表
css·爬虫·python·selenium·html
前端付豪1 小时前
自动学习建议解决薄弱知识点
前端·python·openai
deephub1 小时前
LangGraph vs Semantic Kernel:状态图与内核插件的两条技术路线对比
人工智能·python·深度学习·大语言模型·agent
与虾牵手1 小时前
多轮对话 API 怎么实现?从原理到代码,踩完坑我总结了这套方案
python·aigc·ai编程
geovindu1 小时前
python: Simple Factory Pattern
开发语言·python·设计模式·简单工厂模式
We་ct1 小时前
LeetCode 17. 电话号码的字母组合:回溯算法入门实战
前端·算法·leetcode·typescript·深度优先·深度优先遍历