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)
相关推荐
学术小李1 分钟前
基于Pytorch,如何用CUDA自己写算子?(一)
人工智能·pytorch·python
ShirleyWang01229 分钟前
让headlamp控制台能访问
linux·服务器·python·k8s·k3s
想会飞的蒲公英44 分钟前
用 Streamlit 给文本分类模型做一个演示页面
人工智能·python·机器学习
老徐聊GEO1 小时前
亲测有效的AI品牌检测公司案例分享
大数据·人工智能·python
华研前沿标杆游学1 小时前
2026年企业对标学习TOP7项目:小米数字化考察上榜
python
大模型码小白2 小时前
Spring AI 框架实战:Java 后端集成大模型的架构设计与工程落地
java·人工智能·python·spring
BerryS3N2 小时前
深度解析:从零构建生产级大模型 RAG(检索增强生成)系统全栈指南
开发语言·python·ai
闪电悠米2 小时前
力扣hot100-73.矩阵置零-标记数组详解
算法·leetcode·矩阵
weixin_BYSJ19872 小时前
「课设设计」springboot校园超市助购系统26449 (附源码)
java·javascript·spring boot·python·django·flask·php
今儿敲了吗3 小时前
Python——函数基础
开发语言·笔记·python