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)
相关推荐
xxwl5857 小时前
Python语言初步认识(1)
开发语言·python·学习
古城小栈7 小时前
Python 的主流Ai框架为什么优先适配 Linux 系统?
linux·人工智能·python
财经资讯数据_灵砚智能7 小时前
基于全球经济类多源新闻的NLP情感分析与数据可视化(夜间-次晨)2026年6月15日
大数据·人工智能·python·ai·信息可视化·自然语言处理·灵砚智能
砍材农夫7 小时前
python环境|conda安装和使用(1)
开发语言·后端·python·conda
Odoo老杨7 小时前
如何直接在线定制修改 Odoo UI界面?
css·python·crm·odoo·erp·中小企业数字化
凌波粒7 小时前
LeetCode--90.子集II(回溯算法)
数据结构·算法·leetcode
凌波粒7 小时前
LeetCode--46.全排列(回溯算法)
数据结构·算法·leetcode
派大鑫wink8 小时前
Java 高级编程技巧(生产级实用,覆盖性能、并发、设计、JVM、语法、避坑)
开发语言·python