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 分钟前
【生物医学NLP信息抽取:药物识别、基因识别与化学物质实体识别教程与应用】
python·机器学习·nlp
南_山无梅落9 分钟前
12.Python3函数基础:定义、调用与参数传递规则
python
laocooon5238578861 小时前
插入法排序 python
开发语言·python·算法
wuhen_n2 小时前
LeetCode -- 1:两数之和(简单)
javascript·算法·leetcode·职场和发展
Jeremy爱编码3 小时前
leetcode课程表
算法·leetcode·职场和发展
清水白石0084 小时前
《深入 Python 上下文管理器:contextlib.contextmanager 与类实现方式的底层差异全景解析》
开发语言·python
程序员佳佳4 小时前
GPT-4时代终结?GPT-5.2与Banana Pro实测数据公开,普通开发者如何接住这泼天富贵
开发语言·python·gpt·chatgpt·重构·api·midjourney
努力学算法的蒟蒻4 小时前
day46(12.27)——leetcode面试经典150
算法·leetcode·面试
Blossom.1184 小时前
多模态大模型LoRA微调实战:从零构建企业级图文检索系统
人工智能·python·深度学习·学习·react.js·django·transformer
小钻风33664 小时前
软件测试: 从入门到实践 (接口测试)
软件测试·python