Leetcode迴文數

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

示例 1:

輸入: 121
輸出: true
示例 2:

輸入: -121
輸出: false
解釋: 從左向右讀, 爲 -121 。 從右向左讀, 爲 121- 。因此它不是一個迴文數。
示例 3:

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

//將整數切分後轉爲列表,利用列表的reverse方法判斷。注意reverse()方法的返回值爲null。
//這種方法效率較低
class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        self.x = x
        y = str(x)
        
        a = []
        i = 0
        while(i<len(y)):
            a.append(y[i])
            i+=1
            
        a.reverse()
        
        j = 0
        c = []
        while(j<len(y)):
            c.append(y[j])
            j+=1
            
        if (c == a):
            return True
        else:
            return False
//判斷給定數字是否關於中心對稱
class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        self.x = x
        y = str(x)
        i = 0
        flag = 1
        while(i<len(y)/2):
            if(y[i] != y[len(y)-1-i]):
                flag = 0
                break
            else:
                i+=1
                
        if(flag == 1):
            return True
        else:
            return False
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章