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)
相关推荐
程序员yu29 分钟前
会编网络:别被入门教程骗了,Python实用能力不在语法本身
开发语言·python·学习·算法
鬼手点金32 分钟前
opencode组件详解-安装方式
人工智能·python·优化器·分析器·nanogpt
Bruce_Liuxiaowei42 分钟前
Python 字典默认值完全指南:从 KeyError 到 defaultdict
开发语言·数据结构·python·字典
数据杂坛1 小时前
【Python程序开发系列】一文搞清楚Gunicorn以及和Nginx的区别
python·nginx·gunicorn
zjh9005301 小时前
Visual C++ 2010 安装使用完整包:高手秘籍
python
Allen_LVyingbo1 小时前
信息化部门在AI时代的编程转移路径分析(上)
人工智能·python·算法·健康医疗·数据库开发·时序数据库·数据库架构
用户0332126663671 小时前
Python 实现 Word/TXT 互转:附完整代码
python
常山云栈2 小时前
Anaconda和uv的区别是什么?
python·anaconda·uv
AC赳赳老秦2 小时前
公开 CSV 数据集批量处理实战:用 OpenClaw 高效完成下载、清洗与标准化分析样本生成
java·开发语言·汇编·c++·python·deepseek·openclaw
尹人入圣2 小时前
市面上靠谱的IP驱动产业新场景新工具哪个好
网络·python·网络协议·tcp/ip