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)
相关推荐
winfredzhang6 小时前
用 MediaPipe 手势数字识别一键打开下载夹里的图片(Python + OpenCV 实战)
人工智能·python·opencv·google·mediapipe
某人辛木10 小时前
Web自动化测试
前端·python·pycharm·pytest
C+++Python11 小时前
详细介绍一下Java泛型的通配符
java·windows·python
小帅热爱难回头11 小时前
编写Skill生成AI落地项目系统架构
python
diving deep12 小时前
脚本速览-python
开发语言·python
2601_9516437713 小时前
Python第一,Java跌出前三,C语言杀回来了
java·c语言·python·编程语言排行·技术趋势
AC赳赳老秦16 小时前
OpenClaw+Power Apps 实战:自动生成 Power Apps 应用、连接 Excel 数据源
大数据·开发语言·python·serverless·excel·deepseek·openclaw
一只齐刘海的猫16 小时前
【Leetcode】找到字符串中所有字母异位词
算法·leetcode·职场和发展
茉莉玫瑰花茶17 小时前
综合案例 - AI 智能租房助手 [ 5 ]
服务器·数据库·人工智能·python·ai
文艺倾年17 小时前
【强化学习】强化学习基本概念,20W字总结(一)
人工智能·python·语言模型·自然语言处理·面试·职场和发展·大模型