Python判斷一個數是不是回文數的兩種方法


回文數是指正讀(從左往右)和反讀(從右往左)都一樣的一類數字,例如: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)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM