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)
相关推荐
小南家的青蛙19 分钟前
LeetCode面试题 01.09 字符串轮转
java·leetcode
dudly21 分钟前
Python 字典键 “三变一” 之谜
开发语言·python
元亓亓亓41 分钟前
LeetCode热题100--240.搜索二维矩阵--中等
算法·leetcode·矩阵
小明.杨1 小时前
Django 中时区的理解
后端·python·django
陈奕昆1 小时前
五、【LLaMA-Factory实战】模型部署与监控:从实验室到生产的全链路实践
开发语言·人工智能·python·llama·大模型微调
程序猿小三2 小时前
python uv的了解与使用
开发语言·python·uv
T0uken2 小时前
【Python】UV:单脚本依赖管理
chrome·python·uv
郭逍遥2 小时前
[工具]B站缓存工具箱 (By 郭逍遥)
windows·python·缓存·工具
alpszero3 小时前
YOLO11解决方案之物体模糊探索
人工智能·python·opencv·计算机视觉·yolo11
伊织code3 小时前
PyTorch API 6 - 编译、fft、fx、函数转换、调试、符号追踪
pytorch·python·ai·api·-·6