1. 程式人生 > >Leetcode:9- Palindrome Number

Leetcode:9- Palindrome Number

-s some could urn print def convert ace col

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