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)
相关推荐
All for pursuit.5 分钟前
【动态规划-8】152.乘积最大子数组
数据结构·c++·算法·leetcode·动态规划
JWASX22 分钟前
【agent 开发】Agent 智能体
大数据·人工智能·python
智购科技无人售货机工厂店26 分钟前
玻璃瓶饮料破损率突然上升,排查发现是取货口缓冲垫老化了~YH
java·开发语言·人工智能·python·eclipse
JWASX34 分钟前
【agent 开发】agent 开发学习 - LangChain(2)
python·学习·langchain
kimnoic1 小时前
Python常用标准库模块及查询使用方法
开发语言·python
范中勤1 小时前
Python 与 Java:模块、包、对象、反射核心差异总结
java·python·面试·反射·元类
I Am a robert girl1 小时前
HelixWorld 源码剖析:当世界模型第一次“开口说话”
python·多模态·扩散模型·世界模型·自回归·空间音频·流式推理
棉猴1 小时前
玩游戏学Python6-演员Actor
python·pygame·玩游戏·游戏编程·actor·pgzero
Nil2081 小时前
leetcode 152乘积最大子数组
leetcode
旖旎夜光1 小时前
【LangGraph实战】LangGraph 学习笔记(四):持久化——从线程记忆到跨会话长期记忆
人工智能·笔记·python·学习·ai编程·langgraph