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)
相关推荐
高级程序源20 分钟前
springboot荆州旅游推介平台24175-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·django·课程设计
企业数字化笔记22 分钟前
新租户注册成功却不能用?开通状态、初始化恢复与可用性验收
开发语言·python
Guarding and trust24 分钟前
项目拆解(二):模型输出是‘野‘的——三层兜底+重分析,把AI变成可靠零件
java·人工智能·python·大模型·fastapi·ollama·错误兜底
用户2986985301426 分钟前
Python 实战:将 HTML 内容保存为图像文件
后端·python·html
for_ever_love__27 分钟前
LangChain MultiVectorRetriever:一个文档存多个向量
人工智能·python·自然语言处理·langchain·ai大模型·多向量·摘要检索
迅猛龙办公室33 分钟前
Python实现获取星期字符串
java·前端·python
wewowilling44 分钟前
Coze智能体入门 --- AI Agent开发入门--第一章
python·低代码·agent·零代码·coze
Wx-bishekaifayuan1 小时前
springboot公考微信小程序35511-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游
小猴子爱上树1 小时前
跨马翻译:批量图片翻译+视频字幕+智能抠图,一站式跨境电商翻译工具
python·音视频
溪语流沙1 小时前
【Web全栈进阶】OAuth实战——GitHub第三方登录
前端·python·github