判断回文数字 9. Palindrome Number

2018-06-17 23:25:04来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

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 class Solution:
 2     def isPalindrome(self, x):
 3         """
 4         :type x: int
 5         :rtype: bool
 6         """
 7         if x < 0:
 8             return False
 9         elif x < 10:
10             return True
11         t = x
12         n = 0
13         while t > 0:
14             n += 1
15             t = t // 10
16         for i in range(n // 2):
17             lnum = (x // (10 ** (n-i-1))) % 10
18             rnum = (x // (10 ** i) ) % 10
19             if lnum != rnum:
20                 return False
21         return True

根据数字的位数,从两头开始比较是否相等

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Python pip 下载速度慢? Windows 设置 国内源,用 阿里云 国内镜

下一篇:Python运算符优先级