題目:
找出五位數中的回文數,列印并計算個數。
思路:
回文數是對稱數,指正向讀與反向讀是相同的,如12321,33433等。
是以可以利用正向與反向相同或對稱位數字相同來判斷。
解法1:
利用字元串反轉,判斷反轉前後是否相等
count = 0
for num in range(10000, 99999):
if str(num) == str(num)[::-1]: #str[::-1]表示字元串反轉
print(num)
count += 1
print("共有%d個5位回文數" %(count))
解法2:
利用清單判斷對稱位相等
count = 0 #計數器
for num in range(10000, 99999):
numList = list(str(num))
if numList[0] == numList[4] and numList[1] == numList[3]:
count += 1
print(num)
print("共有%d個5位回文數" %(count))
解法3:
利用清單逆向存儲,判斷逆向前後兩個清單是否相等
count = 0
for num in range(10000, 99999):
numList = list(str(num)) #原數值清單
tmpList = list(str(num)) #逆向存儲後的清單
tmpList.reverse() #reverse()方法進行逆向存儲
if numList == tmpList:
print(num)
count += 1
print("共有%d個5位回文數" %(count))
運作結果:
**
- 題目練習,尚在學習,若有問題請指出。
**