1. 程式人生 > >【LeetCode 9】迴文數

【LeetCode 9】迴文數

題目
判斷一個整數是否是迴文數。
迴文數是指正序(從左向右)和倒序(從右向左)讀都是一樣的整數。

示例

輸入: 121
輸出: true
輸入: -121
輸出: false
解釋: 從左向右讀, 為 -121 。 從右向左讀, 為 121- 。因此它不是一個迴文數。
輸入: 10
輸出: false
解釋: 從右向左讀, 為 01 。因此它不是一個迴文數。

問題解答:

class Solution:
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        str1 = str(x)  
        length = len(str1)
        start=0
        end=length-1
        while start<=end:
            if str1[start]!=str1[end]:
                return False
            else:
                start=start+1
                end=end-1
        return True

解題思路:
將整數轉化為字串,初始化start和end,分別表示字串的開始位置和結束位置的索引,當開始位置的字元與結束位置的字元不相等時,就返回False,否則將start向後挪一位,end向前挪一位再進行判斷。

測試程式