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)
相关推荐
陈同学xxx5 分钟前
Hermes Agent 接入飞书,在手机上随时聊天
linux·python·飞书
卷无止境9 分钟前
Python 中基于 Qt 的 GUI 库授权方式全解析
后端·python
卷无止境23 分钟前
Guardrails.ai:为大语言模型加一道"安全阀"
后端·python
汤姆小白5 小时前
01-环境搭建与项目导览
人工智能·python·机器学习·numpy
伊玛目的门徒9 小时前
试用leetcode之典中典 二数之和问题
java·算法·leetcode
向日的葵00611 小时前
langchain的Tools教程(三)
python·langchain·tools
言乐612 小时前
Python实现可运行解密游戏游戏框架
python·游戏·小程序·游戏程序·关卡设计
Kx_Triumphs12 小时前
HDU4348 To the moon(主席树区间修改模板)
算法·题解
YUS云生13 小时前
Python学习笔记·第31天:FastAPI入门——路由、路径参数、查询参数与请求体
笔记·python·学习
旖-旎13 小时前
《LeetCode647 回文子串 || LeetCode 5 最长回文子串》
c++·算法·leetcode·动态规划·哈希算法