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)
相关推荐
diving deep7 分钟前
从零构建大模型--实操--搭建python环境
开发语言·python
We་ct7 分钟前
LeetCode 172. 阶乘后的零:从暴力到最优,拆解解题核心
开发语言·前端·javascript·算法·leetcode·typescript
老虎062717 分钟前
LeetCode热题100 刷题笔记(第五天)双指针法 「 三数之和 」
笔记·算法·leetcode
qq_白羊座25 分钟前
Langchain、Cursor、python的关系
开发语言·python·langchain
小陈的进阶之路25 分钟前
接口Mock测试
python·mock
kiku181828 分钟前
Python网络编程
开发语言·网络·python
zncxCOS34 分钟前
【ETestDEV5教程30】ICD操作之信号组操作
python·测试工具·测试用例·集成测试
智购科技自动售货机39 分钟前
自动贩卖机厂家哪家价格公道
人工智能·python
美式请加冰42 分钟前
简单多状态问题
数据结构·算法·leetcode
Thomas.Sir44 分钟前
智能革命:AI如何重塑金融风控与信贷审批的底层逻辑
人工智能·python·ai·风控