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)
相关推荐
weixin_447195297 分钟前
【无标题】
pytorch·python
迅猛龙办公室10 分钟前
Python实现简单的人名对话
python
阿坨37 分钟前
firestart:一行命令启动你的日常应用和网页
python·pypi·cli·click
蛋蛋的就会顺顺的41 分钟前
hot100——矩阵
java·数据结构·算法·leetcode·力扣
老歌老听老掉牙1 小时前
麻花钻切屑形态演变的力学机制与临界条件分析
python·算法·钻头
happylifetree1 小时前
Python18(补充):练习
python
weixin_416667962 小时前
银河麒麟V10看门狗试验-1
网络·chrome·python
古城小栈2 小时前
Pydantic 从入门到实践全讲解
python
happylifetree2 小时前
Python18:核心语法-数据存储与运算-运算符-算术运算符
python
打工仔折腾 AI2 小时前
从Attention到BERT:双向预训练语言模型到底解决了什么问题
人工智能·后端·python·深度学习·语言模型·bert