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项目仓库,使用工具:GitHub(远程仓库)、GitHub Desktop(版本控制工具)、VSCode(代码编辑器)
python·编辑器·github
StarPrayers.14 分钟前
PySpark基础知识(python)
python·数据分析·spark
潜龙95271 小时前
第6.2节 Android Agent开发<二>
android·python·覆盖率数据
I'm a winner1 小时前
第五章:Python 数据结构:列表、元组与字典(一)
开发语言·数据结构·python
番薯大佬2 小时前
Python学习-day9 字典Dictionary
网络·python·学习
nightunderblackcat2 小时前
新手向:C语言、Java、Python 的选择与未来指南
java·c语言·python
夏日麋鹿~2 小时前
逐时nc数据批量处理为日平均
python
程序员三明治2 小时前
Python编辑器的安装及配置(Pycharm、Jupyter的安装)从0带你配置,小土堆视频
python·pycharm·编辑器
理想国的女研究僧3 小时前
Jupyter Notebook操作指南(1)
ide·python·学习·jupyter
酷飞飞3 小时前
PyQt 界面布局与交互组件使用指南
python·qt·交互·pyqt