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)
相关推荐
geovindu10 小时前
python:Lasso
开发语言·后端·python·算法
30955666611 小时前
股票数据落库前的去重与主键设计:一次 SQLite 写入实录
java·开发语言·jvm·数据库·redis·python·sqlite
CyrusYiVPP11 小时前
决策树背答案背到 24 片叶子?剪枝三刀砍回 5 片,测试集从 0.749 涨回 0.845,ML数学基础第13期
人工智能·python
用户2986985301411 小时前
Python 批量处理 Word 水印:文字与图片水印的添加及移除
python·api
承渊政道11 小时前
【Python编程快速上手—让繁琐工作自动化】(字典和结构化数据:用键值对搭出棋盘和游戏背包)
python·游戏·pycharm·自动化·字典和结构化数据
Wellijohn11 小时前
让 AI 能改数据库,但不能背着你改:我给 MCP Server 装了一道审批闸
python·架构·mcp
AI创界者11 小时前
【无标题】Python 进阶实战(五十九章):分布式限流、熔断降级与背压控制实战
人工智能·python·aigc
山楂树の12 小时前
Python 函数:参数、作用域、Lambda 与类型注解
开发语言·python
炸薯条!12 小时前
Python装饰器详解:从闭包原理到语法糖,再到多个装饰器
开发语言·python
Zlzxzw13 小时前
Windows 安装WSL
python