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)
相关推荐
科技苑6 小时前
Python简单网络爬虫教程
爬虫·python
mmmmath_38 小时前
LeetCode.541.反转字符串II
数据结构·算法·leetcode
Navigator_Z8 小时前
LeetCode //MySQL - 1251. Average Selling Price
c语言·算法·leetcode
Patrick在香港8 小时前
Claude Prompt 香港场景:公文里「今日」落在 6 个日历日上,「翌日」锚错了 5 天
python·自然语言处理·正则表达式·claude·数据清洗
YsyaaabB9 小时前
Python 数值分析
python
阿洛学长9 小时前
计算机二级 Python 基本操作题(15 分)真题笔记(0101 ~ 1903 全套)
python·pycharm
weixin199701080169 小时前
[特殊字符]️《二手ERP对接电商平台的总体方案:统一数据模型 + 事件驱动 + 灰度上线6原则》(附Python源码)
大数据·python
滚雪球~10 小时前
量化交易 防止Windows电脑自动更新并重启
python·量化
参.商.10 小时前
【Day 53】76. 最小覆盖子串
leetcode·golang
L@ncor11 小时前
第二章可能出现的问题
人工智能·python