Question:
求是否是回文,顾名思义就是返过来也是相同的数。
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121 Output: true
Example 2:
Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:
Coud you solve it without converting the integer to a string?
Code:
class Solution: def isPalindrome(self, x): """ :type x: int :rtype: bool """ if list(str(x))[::-1] == list(str(x)): return True else: return False def isPalindrome2(self,x): if x < 0 or (x % 10 == 0 and x != 0): return False reverted_number = 0 while x > reverted_number: reverted_number = reverted_number * 10 + x % 10 x = int(x/10) return x == reverted_number or x == int(reverted_number / 10) s = Solution() print("The first method:") print(s.isPalindrome(121)) print(s.isPalindrome(-121)) print(s.isPalindrome(10)) print(s.isPalindrome(11)) print("The second method:") print(s.isPalindrome2(121)) print(s.isPalindrome2(-121)) print(s.isPalindrome2(10)) print(s.isPalindrome2(11))
Result:
The first method:
True
False
False
True
The second method:
True
False
False
True
第一个方法是通过int转str,再转list,再颠倒一下list。这个方法题目中有提到不可用。
第二个方法就是类似于第六题中,反转方法,负数一律不是回文。对于正数,如果后半段反转得到的是和剩下前半段一样就说明是回文。
那么什么时候判断是一半呢,就是前半段已经小于后半段时,就反转了一半了。
如果长度是偶数,那么前一半和后一半的反转是一样的,如果长度是奇数,那么前一半和后一半(多出一位)除以10是一样的。既不看中间那位,前后是一样的。
第二个方法复杂度:
-
Time complexity : O(log10(n)). We divided the input by 10 for every iteration, so the time complexity isO(log10(n))
-
Space complexity : O(1).