要求:
回文数是指从前往后读和从后往前读都是一样的数字,比如 121。 最近的回文数指的是离给定数字最近的回文数,比如给定数字 125,最近的回文数是121。
编写一个程序,查找离给定整数最近的回文数。
- 定义函数
find_closest_palindrome()
,参数为num
。 - 在函数内部,返回最近的回文数。如果有两个回文数的绝对距离相同,返回较小的数。
- 如果给定数字本身就是回文数,则返回该数字。
示例输入
245
示例输出
242
解释: 测试输入 245 的最近回文数是 242。
- 已经定义了函数
is_palindrome()
,用于判断一个数字是否是回文数。
代码:
def is_palindrome(n):
return str(n) == str(n)[::-1]
# 定义函数
def find_closest_palindrome(num):
if is_palindrome(num):
return num
lower = num - 1
upper = num + 1
while True:
if is_palindrome(lower):
# 如果 lower 是回文数,则返回 lower
return lower
elif is_palindrome(upper):
# 如果 upper 是回文数,则返回 upper
return upper
else:
# 否则继续向外扩展搜索
lower -= 1
upper += 1
# 从用户处获取输入
num = int(input())
# 调用函数
print(find_closest_palindrome(num))