【LeetCode 9】回文数

版权声明:本文为博主原创文章,转载请注明出处,谢谢大家O(∩_∩)O https://blog.csdn.net/Stripeybaby/article/details/81275359

题目
判断一个整数是否是回文数。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。

示例

输入: 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向前挪一位再进行判断。

测试程序

猜你喜欢

转载自blog.csdn.net/Stripeybaby/article/details/81275359