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)
相关推荐
郑洁文12 小时前
基于Python的网络入侵检测系统
网络·python·php
AIMath~12 小时前
python中的uv命令揭秘
开发语言·python·uv
弹简特12 小时前
【零基础学Python】06-Python模块和包、异常处理、文件常用操作
开发语言·python
念恒1230613 小时前
Python 面向对象编程核心:对象、实例化、封装与变量作用域
开发语言·python
薛定谔的悦13 小时前
光伏-储能-负荷联合预测:给 EMS 装上“预知能力“
java·数据库·人工智能·python·储能
memcpy013 小时前
LeetCode 2144. 打折购买糖果的最小开销【贪心】
算法·leetcode·职场和发展
Metaphor69214 小时前
使用 Python 在 Excel 中查找并高亮显示
python·信息可视化·excel
旦莫14 小时前
AI测试Agent的两种架构路径:谁做主控?
人工智能·python·架构·自动化·ai测试
散峰而望14 小时前
【算法练习】算法练习精选:陶陶摘苹果(基础+升级)、Music Notes、字串变换,你能AC几道?
数据结构·c++·算法·leetcode·贪心算法·github·动态规划
搬石头的马农14 小时前
从零配置Claude自动修Bug:6步打造全自动开发流程
java·人工智能·python·bug·ai编程