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)
相关推荐
2501_947575802 小时前
计算机毕业设计之jsp开山车行二手车交易系统
java·开发语言·hadoop·python·信息可视化·django·课程设计
Byron__3 小时前
AI学习_06_短期记忆与长期记忆
人工智能·python·学习
取经蜗牛4 小时前
Python 第一阶段完全指南:从零到第一个实用工具
开发语言·python
创世宇图4 小时前
【Python工程化实战】OpenTelemetry 在 Python 中的全链路追踪落地:从埋点到可视化的完整实战指南
python·分布式链路追踪·性能监控·opentelemetry·微服务可观测性
许彰午5 小时前
72_Python爬虫基础BeautifulSoup
爬虫·python·beautifulsoup
zhanghongyi_cpp6 小时前
10. 实验书3.4.2 筛选达到预警阈值的病虫害数据
python
tuddy7894646 小时前
Codex++ 安全边界探秘:从模型能力到风险防御
人工智能·python·安全
C++、Java和Python的菜鸟6 小时前
第1章 集合高级
java·jvm·python
第六五6 小时前
Python 内置装饰器
开发语言·python
梦帮科技6 小时前
UE5 GAS 实战:用 Gameplay Ability System 搭建「赛博修真」境界与技能体系
c++·人工智能·python·ue5·c#