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)
相关推荐
用户019027581612 小时前
AlphaFeed 查不到代码返回空?非法/缺后缀 symbol 的行为与处理
python
isfox2 小时前
Python 单元测试:别再用 print 调试了,写个测试一劳永逸
python
用户298698530142 小时前
在 Python 中把 Word 文档转换为 JSON 的三种实现方式
python·json·api
用户0332126663673 小时前
使用 Python 删除 Excel 中的空白行或空白列
python·excel
databook3 小时前
时间序列特征,哪些当时就能算出来
python·数据分析
kevin_org3 小时前
LangChain入门学习(四)
python·学习·langchain·fastapi
Pniubi4 小时前
01背包类问题-力扣416.分割等和子集
算法·leetcode·职场和发展
特立独行的猫A11 小时前
别再用 nohup 了:让应用在后台常驻的正确姿势与 systemd 服务详解
java·后端·python
吃我一窝jio14 小时前
Python与Go线程模型深度对比
java·开发语言·python
文丑颜不良啊15 小时前
LeetCode3041~3060题目解析
java·leetcode