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)
相关推荐
2601_9623008119 小时前
机器学习贴士:使用Python编写MapReduce
hadoop·python·机器学习·mapreduce·数据处理
xyz_CDragon20 小时前
GitHub上4个爆款AI开源Skill:拍照后不用P图,用Codex一键生成高级海报(附效果图+使用教程)
人工智能·python·github·codex·skill
weixin1997010801620 小时前
[特殊字符]《跨境二手ERP对接Back Market:标准化API + 7~10工作日技术合规审核实录》(附Python源码)
开发语言·python·pandas
持敬chijing21 小时前
Python-数据类型-列表
开发语言·python·青少年编程
2601_9623010121 小时前
Python环境搭建及PyCharm破解使用技巧
python·pycharm·环境搭建·避坑技巧·破解使用
Navigator_Z1 天前
LeetCode //C - 1240. Tiling a Rectangle with the Fewest Squares
c语言·算法·leetcode
稻米哟1 天前
力扣100——双指针
算法·leetcode
2601_962099461 天前
Python中的find()函数:用法和示例
python·字符串·索引·子字符串·find函数
大圣编蚕1 天前
Java StringWriter 详解:从入门到实战
java·开发语言·python
for_ever_love__1 天前
python基础语法学习: requirements.txt
开发语言·python·学习