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)
相关推荐
文人sec29 分钟前
pytest1-接口自动化测试场景
软件测试·python·单元测试·pytest
希望有朝一日能如愿以偿2 小时前
力扣每日一题:仅含1的子串数
算法·leetcode·职场和发展
secondyoung2 小时前
Mermaid流程图高效转换为图片方案
c语言·人工智能·windows·vscode·python·docker·流程图
nini_boom2 小时前
**论文初稿撰写工具2025推荐,高效写作与智能辅助全解析*
大数据·python·信息可视化
苏小瀚3 小时前
算法---FloodFill算法和记忆化搜索算法
数据结构·算法·leetcode
1***s6323 小时前
Python爬虫反爬策略,User-Agent与代理IP
开发语言·爬虫·python
咖啡の猫4 小时前
Python的自述
开发语言·python
重启编程之路5 小时前
python 基础学习socket -TCP编程
网络·python·学习·tcp/ip
云和数据.ChenGuang6 小时前
pycharm怎么将背景换成白色
ide·python·pycharm