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)
相关推荐
weelinking5 小时前
【产品】12_接入数据库——让数据永久保存
jvm·数据库·python·react.js·数据挖掘·前端框架·产品经理
程序大视界6 小时前
【Python系列课程】Python正则表达式(下):环视、命名分组与日志实战
开发语言·python·正则表达式
TickDB6 小时前
美股行情 API 接入避坑:REST 快照、WebSocket 推送、盘前盘后数据的边界
人工智能·python·websocket·行情数据 api
枫叶v.6 小时前
Agent 分层存储架构设计:从记忆方法到中间件选型
开发语言·python
水兵没月6 小时前
逆向实战小记——某ToB商城网站分析学习
python·网络爬虫
程序员小远7 小时前
Python自动化测试框架及工具详解
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
sleven fung7 小时前
MinerU与BabelDOC与KTransformers与OpenAI API库
开发语言·python·ai·langchain
小毛驴8508 小时前
spring-boot-maven-plugin,maven-compiler-plugin 功能对比
java·python·maven
萤萤七悬8 小时前
【Python笔记】AI帮实现CLI工具-使用argparse.ArgumentParser接收命令参数
开发语言·笔记·python
啦哈拉哈8 小时前
Leetcode题解记录-hot100(81-100)
算法·leetcode·职场和发展