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?
MyThought:
先得出该数字有几位,然后逐层比较两边的数字是否相等,然后去除两边数字进行循环判断。O(n)
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False # 有负号就不是
# x的位数
lens,y = 0,x
while y != 0:
lens += 1
y //= 10
while x//10**(lens-1) == x % 10 and x != 0:
x = (x - x // 10**(lens-1) * 10**(lens-1))//10
lens -= 2
return True if x == 0 else False
执行内存:136ms,击败8.85%用户
内存消耗:13.8MB,击败5.20%用户
计算整数位数还可以使用以10为底的log函数解决。log10(三位数) = 2.多,因为102~103之间的数都是三位数,so可以用以十为底的log函数来求整数的位数。
New Thought:
回文数,不光可以两边对称的看,他还可以从中间截开,将另一部分反转再与前一部分比较是否一致,也是一种很好的思路。
比我的思路要快一些
import math
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0 or (x % 10 == 0 and x != 0):
return False # 有负号就不是
if x == 0:
return True
lens = int(math.log(x,10))+1 # x的位数
reverse_x = 0
while x > reverse_x:
reverse_x = reverse_x * 10 + x % 10
x //= 10
return True if x == reverse_x or reverse_x // 10 == x else False
执行内存:88ms,击败44.85%用户
内存消耗:13.6MB,击败5.20%用户