[LeetCode] 564. Find the Closest Palindrome 深入浅出讲解和代码示例

本文介绍了一种寻找给定整数最近回文数的方法。通过遍历从给定整数开始递减的数,判断其是否为回文数,从而找到最接近的回文数。若存在多个相同距离的回文数,则返回较小的那个。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、汇总概要

xx

2、题目

Given an integer n, find the closest integer (not including itself), which is a palindrome.

The 'closest' is defined as absolute difference minimized between two integers.

Example 1:

Input: "123"
Output: "121"

Note:

  1. The input n is a positive integer represented by string, whose length will not exceed 18.
  2. If there is a tie, return the smaller one as answer.

3、审题

给定一个整数,求出它最近的回文串

4、解题思路

该题较简单,直接上代码。

5、代码示例 - Python

class Solution(object):
    def nearestPalindromic(self, n):
        for i in range(n,1,-1):
            istr = str(i)
            leng = len(istr)
            flag = 1
            for j in range(0,leng/2):
                if istr[j] != istr[leng-1-j]:
                    flag = 0
            if flag == 1: #is the palindromic 
                return i
if __name__ == "__main__":
    st = Solution()
    res = st.nearestPalindromic(15500987)
    print "\nres-------: ",res


---------------------------------------------------------------------------------------------------

本文链接:http://blog.youkuaiyun.com/karen0310/article/details/xx

请尊重作者的劳动成果,转载请注明出处!

---------------------------------------------------------------------------------------------------


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值