zoukankan      html  css  js  c++  java
  • Palindrome Number

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

    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.

    这题要求判断一个数字是否是回文,很有意思,也充满陷阱。题目提示:首先为负数的时候是否为回文,我个人觉得不可以。其次,如果使用Reverse Interger的做法先反转数字,之后判断原数和反转后的数字是否相等的思路,可能会遇到溢出的问题(不过如果溢出肯定不是回文,可以提前排除)。

    另外如果数字不止一位,但是结尾为0,也可以提前判断不是回文。

    解法一:也是我看到这题的第一思路,从两边往中间逐位比较,遇到不相等的肯定不是回文。取数的过程中也有技巧,一个是先需要获得数字本身的位数,即取完两边的数之后,去掉两头的数,这样方便以后的继续比较。代码为:

    class Solution(object):
        def isPalindrome(self, x):
            """
            :type x: int
            :rtype: bool
            """
            if x<0 or (x!=0 and x%10==0):
                return False
            y = 1
            while x/y>=10:
                y *= 10
            while x:
                if x/y != x%10:
                    return False
                else:
                    x = (x%y)/10
                    y /=100
            return True

    可以看到y为和x位数一样的10的幂次数。取完首尾比较后x = (x%y)/10,将首尾砍去,之后继续进行比较。时间复杂度为O(n),空间复杂度为O(1).

    解法二:来自leetcode的高票答案,即从尾部开始反转一半数字。偶数的话比较反转的这一半数字和留下的数字是否相等,奇数的话比较反转的值除去最后一位是否等于留下的数。相比于解法一,免去了先获取y的过程(复杂度O(n)).后面因为只有反转完一半之后才可以比较,不存在中途退出机制,所以其实解法一快于解法二。代码如下:

    class Solution(object):
        def isPalindrome(self, x):
            """
            :type x: int
            :rtype: bool
            """
            if x<0 or (x!=0 and x%10==0):return False
        
            sum = 0
            while sum < x:
                sum = sum*10+x%10
                x = x/10
            return sum==x or sum/10==x
  • 相关阅读:
    nodeJS从入门到进阶三(MongoDB数据库)
    nodeJS从入门到进阶二(网络部分)
    nodeJS实现简易爬虫
    nodeJS从入门到进阶一(基础部分)
    js节流与防抖函数封装
    React16源码解读:揭秘ReactDOM.render
    React16源码解读:开篇带你搞懂几个面试考点
    TypeScript高级用法详解
    一文搞懂V8引擎的垃圾回收
    JavaScript的内存模型
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5439514.html
Copyright © 2011-2022 走看看