Leetcode:9- Palindrome Number

Posted zj83839

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode:9- 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.

上面这一段告诉我们:1,负数都不是回文数;2,不能通过将数字转为字符串来判断回文,因为使用了额外的空间(即只能使用空间复杂度 O(1) 的方法);3,注意整数溢出问题;4,这个问题有一个比较通用的解法。

题意:判断一个整数是否是回文整数。

思路1:将整数反转,看与原数是否相等

 

 1 class Solution(object):
 2     def isPalindrome(self, x):
 3         if x < 0:
 4             return False
 5         tmp = x  #复制x
 6         y = 0
 7         while tmp:
 8             y = y*10 + tmp%10
 9             tmp = tmp//10  #此处用整数出发
10         return y == x  #x的反向等于x本身,则回文
11 if __name__==__main__:
12     solution = Solution()
13     x = 121
14     print(solution.isPalindrome(x))

 

思路2:从两头往中间逐位判断

 1 class Solution(object):
 2     def isPalindrome(self, x):
 3         if x < 0:
 4             return False
 5         count = 1
 6         while x // count >= 10:
 7             count = count * 10  #得到x的位数
 8         while x:
 9             left = x % 10       #获取首位值,逐个对比
10             right = x // count
11             if left != right:
12                 return False
13             x = (x % count) // 10
14             count = count // 100
15         return True
16 if __name__==__main__:
17     solution = Solution()
18     x = 120021
19     print(solution.isPalindrome(x))

 

 

 

以上是关于Leetcode:9- Palindrome Number的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 9. Palindrome Number

LeetCode - 9 - Palindrome Number

Leetcode:9- Palindrome Number

leetcode-9 Palindrome Number

Leetcode 9. Palindrome Number

leetcode 9. Palindrome Number