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)
相关推荐
Want5951 小时前
Python太极八卦图
开发语言·python
川石课堂软件测试1 小时前
自动化测试|持续集成Git使用详解
git·python·jmeter·mysql·ci/cd·容器·kubernetes
饕餮争锋1 小时前
python开发工具uv简介
开发语言·python·uv
znx9391 小时前
量化交易:用理性穿越市场混沌的修行之路
人工智能·python·机器学习·期魔方
兔子零10241 小时前
FastAPI 零基础入门教程:写过 Node.js,就能轻松学会 Python 后端开发(一)
前端·后端·python
Marst Code2 小时前
上位机开发日记 · 第 12 篇 · 测试:设备模拟器是核心资产
python
坊钰2 小时前
【LangGraph框架入门级】4. 支持联网搜索的智能代理系统
python·ai编程·langgraph
Tisfy2 小时前
LeetCode 3727.最大交替平方和:排序 (双指针可选)
算法·leetcode·题解·贪心·数组·排序
运维@小兵2 小时前
安装Pycharm并破解
ide·python·pycharm
冬、不眠的夜2 小时前
Nuitka 将 python 程序编译成 exe 指南
开发语言·python