leetcode_9. Palindrome Number 判断一个整数是否是回文串数字

来源:互联网 发布:股票资金走势图软件 编辑:程序博客网 时间:2024/05/24 01:48

题目:

Determine whether an integer is a palindrome. Do this without extra space.

click to show spoilers.

Some hints:

Could negative integers be palindromes? (ie, -1)

If you are thinking of converting the integer to string, note the restriction of using extra space.

You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?

There is a more generic way of solving this problem.


题意:

给定一个整数,判断该整数是否是回文串数字,不要使用额外的空间


代码:

class Solution(object):
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        
        if x < 0 :
            return False
        else :
            k = 1
            while x/k >= 10 :             #k后面的0的个数代表整数x最高位后面的位数,x/k即可得到x的最高位数字,x/k >= 10中的等号不要漏掉
                k = k*10
            while k > 1 :           #k>1,表示x不是个位数,仍要进行比较是否是回文串
                upx = x/k             #得到x的最高位
                lowx = x%10          #得到x的最低位
                if upx != lowx :                 #判断是否相等
                    return False
                x = (x%k)/10             #新的x等于原来的x去掉首尾后的值
                k = k/100                    #新的k也要去掉后面两个0,代表新的x的位数减少了两位
            return True
                

笔记:

1、用一个变量k来记录x最高位对应的10的倍数,然后用x/k 可以很容易得到x的最高位

2、新的x赋值的时候,先用x=x%k得到除去最高位后的数,再用/10去掉个位,最后即得去掉首尾的数





0 0
原创粉丝点击