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 小时前
Python 面向对象高级:继承与类定义详解
开发语言·python
凯瑟琳.奥古斯特3 小时前
高阶子查询题目精炼
开发语言·数据库·python·职场和发展·数据库开发
风之所往_4 小时前
Python 3.4 新特性全面总结
python
叶小鸡4 小时前
小鸡玩算法-力扣HOT100-多维动态规划
算法·leetcode·动态规划
太阳上的雨天4 小时前
任何格式的文件转Markdown
python·ai
yaoxin5211235 小时前
419. 现代 Java IO 最佳实践 - 写入文本文件
java·windows·python
菜菜的顾清寒5 小时前
力扣HOT100(42)链表-随机链表的复制
算法·leetcode·链表
weixin_468466855 小时前
纳米 AI 搜索新手极速上手指南
人工智能·python·深度学习·搜索引擎·ai·语言模型·自然语言处理
凯瑟琳.奥古斯特5 小时前
数据库原理选择题精选
数据库·python·职场和发展