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

题目:

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值