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)
相关推荐
Nil20813 分钟前
leetcode 48旋转图像
算法·leetcode·职场和发展
Nil20831 分钟前
leetcode 206反转链表
算法·leetcode·链表
qxqycb31 分钟前
python一键反编译工具
python
weixin_BYSJ198739 分钟前
springboot技能与工具共享小程序---附源码29657
java·javascript·spring boot·python·小程序·django·php
weixin_BYSJ19871 小时前
flask民族服饰饰品商城小程序---附源码37399
java·javascript·spring boot·python·小程序·django·php
帅气的小峰1 小时前
pybind11与nanobind可以共存吗?如何迁移?
c++·python·cuda·推理引擎
用户298698530141 小时前
从入门到自动化:TXT 转 Word 的在线工具与代码实战方案
人工智能·后端·python
W_326001 小时前
Python-OpenCV:库、环境搭建、图片与摄像头解析
开发语言·图像处理·python·opencv·机器学习
抓不住时间的沙2 小时前
N1搭建Hexo个人博客,部署到Github
python·docker·node.js·debian·github·arm
W_326002 小时前
Python-OpenCV:画布、图形、文字、调色滑动条
图像处理·python·opencv·机器学习·计算机视觉