码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode:9- Palindrome Number

时间:2017-12-27 14:29:30      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:pos   integer   对比   回文数   while   tco   有一个   over   and   

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

标签:pos   integer   对比   回文数   while   tco   有一个   over   and   

原文地址:https://www.cnblogs.com/zj83839/p/8124755.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!