Python判断数字回文(转字符串实现,不转字符串实现)

Python实现数字回文的判断,回文返回True,非回文返回False, 只有一位数的也返回True.

其中思路一,将数字转换成字符串,然后跟逆序对比,但需要额外的空间开销来创建字符串。具体实现:

def isPalindrome(x):
"""
:type x: int
:rtype: bool
"""
str_x = str(x)
if len(str_x) == 0:
print("Input {0} is invalid.".format(x))
return False
return str_x == str_x[::-1]


if __name__ == '__main__':
input_str = input("Please input one number:")
try:
x = int(input_str)
print(isPalindrome(x))
except ValueError:
print("Input {0} is invalid.".format(input_str))


猜你喜欢

转载自www.cnblogs.com/kaiying-Tang/p/11511192.html
今日推荐