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)
相关推荐
信誓旦旦的程序猿12 小时前
【Python量化实战宝典 #20】动量、反转择时手册:趋势跟随与均值回归(Python 可跑)
java·python·股票数据api·股票数据api接口·股票api数据接口·股票量化数据api·股票量化数据接口
好焊孙辉12 小时前
从六代螺柱焊机到AI质检:鸿栢科技的螺柱焊国产化路径
人工智能·python·科技·fpga开发
benchmark_cc12 小时前
个人量化系统搭建:如何利用 QuantDash 实现 A 股日 K 线前复权数据的高效获取与质量校验?
python·数据分析·pandas·量化交易·股票数据·quantdash
hhb_61812 小时前
Python异步队列实战:高效处理耗时任务
开发语言·python
2601_9628857212 小时前
一个接口取 A 股+美股+港股:多市场数据方案对比
python
SEO_juper13 小时前
Node.js 全站死链检测工具:从 sitemap 出发一次找全 404
开发语言·人工智能·python·node.js·seo·外贸独立站
ljt272496066113 小时前
Python笔记(九)--asyncio
笔记·python
老孟说禅13 小时前
自动化测试实战(二)
python
2601_9679873713 小时前
你们都用Python实现了哪些自动化办公?
python·excel·自动化办公·1024程序员节·学习资料·跨平台操作
wflynn13 小时前
GitHub 今日推荐|Snapintosh:用 ARM EL2 监控器骗过内核,让骁龙芯片笔记本跑 macOS
python·开源·github