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)
相关推荐
小熊Coding6 分钟前
童年游戏冒险岛(Python版本)
python·游戏·pygame
WJ.Polar25 分钟前
Scapy基本应用
linux·运维·网络·python
H_unique44 分钟前
LangChain:调用工具Ⅲ
python·langchain
醉舞经阁半卷书11 小时前
深入掌握LangChain
python·langchain
CDN3601 小时前
[硬核] 你的DNS正在“裸奔”?用Python手撕DNS劫持与隧道检测逻辑
开发语言·网络·python
kybs19912 小时前
springboot视频推荐系统--附源码72953
java·spring boot·python·eclipse·asp.net·php·idea
BU摆烂会噶3 小时前
【LangGraph】运行时上下文(Runtime Context)
人工智能·python·langchain
xingbuxing_py3 小时前
精华贴分享|北交所:小市值策略的“甜蜜陷阱”还是“弹性引擎”?——一份轻度理解
python·金融·股票·理财·量化投资·股市·炒股
yj15583 小时前
在装修预算有限的情况下,哪些地方可以省?
python
TickDB3 小时前
Python 接入国内期货 Tick 行情:从 CTP 到统一 API 的工程实践
python·websocket