回文數是指正讀(從左往右)和反讀(從右往左)都一樣的一類數字,例如:12321、1221等。小數不是回文數。Python有很多方法判斷一個數是不是回文數,現在只介紹其中兩種。
"""
判斷一個數是不是回文數,列表切片
"""
def is_palindrome(num):
n = list(str(num))
tmp = int("".join(n[::-1]))
#print("num = %d, tmp = %d" %(num, tmp))
return num == tmp
"""
判斷一個數是不是回文數,整數取余取整
"""
def is_palindrome(num):
temp = num
total = 0
while temp > 0:
total = total * 10 + temp % 10
temp //= 10
# print(num, total)
return total == num
if __name__ == "__main__":
num = int(input("請輸入一個正整數,num = "))
if is_palindrome(num):
print("%d 是回文數!" % num)
else:
print("%d 不是回文數!" % num)