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)
相关推荐
万粉变现经纪人3 分钟前
如何解决 pip install cx_Oracle 报错 未找到 Oracle Instant Client 问题
数据库·python·mysql·oracle·pycharm·bug·pip
sw1213893 分钟前
使用Plotly创建交互式图表
jvm·数据库·python
2301_810160956 分钟前
如何为开源Python项目做贡献?
jvm·数据库·python
若惜6 分钟前
selenium自动化测试web自动化测试 框架封装Pom
前端·python·selenium
weixin_4577600012 分钟前
基于pytorch实现LPR模型车牌识别
人工智能·pytorch·python·深度学习·lpr
_日拱一卒13 分钟前
LeetCode:字母异位词分组
算法·leetcode·职场和发展
Zaly.15 分钟前
【Python刷题】LeetCode 3567 子矩阵的最小绝对差
python·leetcode·矩阵
2501_9454235421 分钟前
使用PyTorch构建你的第一个神经网络
jvm·数据库·python
Morwit23 分钟前
*【力扣hot100】 215. 数组中的第K个最大元素
数据结构·c++·算法·leetcode·职场和发展
吃杠碰小鸡23 分钟前
Python+Ai学习流程
人工智能·python·学习