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)
相关推荐
摸鱼仙人~13 分钟前
一文详解PyTorch DDP
人工智能·pytorch·python
超级种码14 分钟前
Java:JavaAgent技术(java.instrument和java.attach)
java·开发语言·python
LYFlied1 小时前
【每日算法】LeetCode 64. 最小路径和(多维动态规划)
数据结构·算法·leetcode·动态规划
Salt_07281 小时前
DAY44 简单 CNN
python·深度学习·神经网络·算法·机器学习·计算机视觉·cnn
Iridescent11211 小时前
Iridescent:Day35
python
a程序小傲1 小时前
阿里Java面试被问:.Java 8中Stream API的常用操作和性能考量
开发语言·windows·python
智航GIS2 小时前
2.3 运算符详解
开发语言·python
屋顶那猫2 小时前
使用pyinstaller打包pytest项目
python·pytest
web3.08889992 小时前
接入API-自动化批量获取淘宝商品详情数据
开发语言·python
sin_hielo2 小时前
leetcode 3074
数据结构·算法·leetcode