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)
相关推荐
8Qi86 小时前
回文子串(Palindromic Substrings)—— 题解
算法·leetcode·职场和发展·动态规划
珺毅同学9 小时前
YOLO生成预测json标签迁移问题
python·yolo·json
骑士雄师9 小时前
18.4 长期记忆可修改版
python
~小先生~9 小时前
Python从入门到放弃(一)
开发语言·python
天佑木枫10 小时前
第2天:变量与数据类型 —— 让程序记住信息
python
Dust-Chasing11 小时前
Claude Code源码剖析 - Claude Code 上下文压缩机制
人工智能·python·ai
小欣加油11 小时前
leetcode1926 迷宫中离入口最近的出口
数据结构·c++·算法·leetcode·职场和发展
Cloud_Shy61812 小时前
解读《Effective Python 3rd Edition》:从练气到老魔(第五章 Item 33 - 35)
开发语言·人工智能·笔记·python·学习方法
abcy07121312 小时前
python pandas csv异步后台清洗前端优先返回成功信息
前端·python·pandas
颜酱13 小时前
LangChain使用RAG 入门:让大模型读懂你的私有文档
python·langchain