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)
相关推荐
学电子她就能回来吗28 分钟前
LeetCode Hot 100|普通数组专题学习笔记(零基础版)
笔记·算法·leetcode
估值探索者41 分钟前
【Python量化选股流水线 #04】选股器好不好用?「昨日候选→今日表现」回看验收
开发语言·python·股票数据·股票数据api接口
田里的水稻1 小时前
PyTorch_Dataloader\TensorBoard---数据加载与可视化
人工智能·pytorch·python·神经网络·机器学习
Dmz丶1 小时前
前端转 AI 100 天 Day 27:Docker 容器化——从“我电脑能跑“到“到处能跑“
python
卿卿的产品经理日记1 小时前
【AI产品经理实战】Day 38|try-except 踩坑实录:报错是数据
人工智能·笔记·python·学习·产品经理
全栈练习生2 小时前
文档智能与实践
python·ai
隐擎fox2 小时前
深入 Android 移动端风控与协议层对抗:内核级虚拟环境检测、网络堆栈特征伪装与住宅 IP 协同实战
android·网络·python·网络协议·tcp/ip
“AI国潮设计-小江”2 小时前
【AIGC实战】Python+SDXL批量生成「潮汕英歌舞冰淇淋蛋糕&红桃粿咖啡」IP,固定角色形象批量出甜品商业效果图
开发语言·人工智能·python·prompt·aigc
Merrill_hh3 小时前
Python环境搭建
python
用户019027581613 小时前
如何用 Python 回测布林带突破策略?
python