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)
相关推荐
xwill*5 小时前
分词器(Tokenizer)-sentencepiece(把训练语料中的字符自动组合成一个最优的子词(subword)集合。)
开发语言·pytorch·python
咖啡の猫6 小时前
Python列表的查询操作
开发语言·python
Chiandra_Leong6 小时前
Python-Pandas、Numpy
python·pandas
BoBoZz196 小时前
ParametricObjectsDemo多种参数曲面展示及面上部分点法线展示
python·vtk·图形渲染·图形处理
quikai19816 小时前
python练习第三组
开发语言·python
ULTRA??7 小时前
初学protobuf,C++应用例子(AI辅助)
c++·python
CHANG_THE_WORLD7 小时前
Python 字符串全面解析
开发语言·python
努力学算法的蒟蒻7 小时前
day27(12.7)——leetcode面试经典150
算法·leetcode·面试
甄心爱学习8 小时前
CSP认证 备考(python)
数据结构·python·算法·动态规划
databook8 小时前
数据会说谎?三大推断方法帮你“审问”数据真相
后端·python·数据分析