Python實現數字迴文的判斷,迴文返回True,非迴文返回False, 只有一位數的也返回True.orm
其中思路一,將數字轉換成字符串,而後跟逆序對比,但須要額外的空間開銷來建立字符串。具體實現:字符串
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))