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)
相关推荐
雨墨✘14 分钟前
CSS如何提高团队协作效率_推广BEM规范减少样式沟通成本
jvm·数据库·python
hef28819 分钟前
如何实现SQL字段值的计算输出:算术运算符与别名结合
jvm·数据库·python
2401_8274999919 分钟前
python项目实战11-正则表达式基础
python·mysql·正则表达式
小糖学代码30 分钟前
LLM系列:1.python入门:6.元组型对象(tuple)
linux·运维·服务器·python
ZC跨境爬虫30 分钟前
Scrapy实战:5sing原创音乐网多页数据爬取(完整可运行,附避坑指南)
爬虫·python·scrapy·html
西西弗Sisyphus38 分钟前
Python dataclasses 中 field 的 default_factory 参数用法
python·field·dataclasses·default_factory
yuyuyuliang001 小时前
python笔记1
开发语言·笔记·python
摇滚侠1 小时前
Groovy 如何给集合中添加元素
java·开发语言·windows·python
.柒宇.1 小时前
力扣hot100之最大子数组和(Java版)
数据结构·算法·leetcode
AI效率工坊1 小时前
【Python实战】数据可视化自动化:matplotlib+pyecharts+AI智能推荐图表类型
python·信息可视化·自动化