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)
相关推荐
海宇数据几秒前
零信任架构实战:基于海宇柠檬查出险-登记证构建自动化残值评估网关
人工智能·python·架构·自动化
李可以量化9 分钟前
Tornado 如何增加网页操作(下)
python
zhangzeyuaaa31 分钟前
深入理解 pip install .:安装当前目录项目的正确姿势
人工智能·python·pip
Jazz_z1 小时前
纯 Python 环境下 Excel 文件的读取与导入详解
python
Thomas.Sir1 小时前
第38课:TensorFlow|可视化工具TensorBoard全用法【日志写入、指标监控、网络可视化】
人工智能·python·tensorflow
SEO_juper2 小时前
外贸多语言站最隐蔽的流量杀手:hreflang 错了,谷歌把德语页推给美国人(附审计脚本)
开发语言·前端·python·seo·独立站·谷歌优化
Metaphor6922 小时前
快速合并 Word 文档【Python 指南】
python·word
JAVA老架构AI智能化2 小时前
如何高质量分块
人工智能·python
泡海椒2 小时前
告别反射低效:JQuick-Java ASM动态调用链性能优化实战
java·python·性能优化