1. 整数反转
给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。假设环境不允许存储 64 位整数(有符号或无符号)。
方法1:转list
分析方法
# 速度很快,内存占用较大
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x >= 0:
li = list(str(x))
li.reverse()
else:
li = list(str(x))[1:]
li.reverse()
li.insert(0, '-')
x = int(''.join(li))
if not -pow(2, 31) <= x <= pow(2, 31) - 1:
return 0
else:
return x
方法2:
# 复杂
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
sign = 1
if x < 0:
x = abs(x)
sign = -1
temp = x % 10
sum = 0
while x:
x = x // 10
sum = temp + sum * 10
temp = x % 10
if not -pow(2, 31) <= sum <= pow(2, 31) - 1:
return 0
else:
return sum * sign
方法3
# 节约了内存,速度会慢
class Solution:
def int_reverse(self, x):
new_x = abs(x)
res = 0
while new_x != 0:
temp = new_x % 10
if (res > 214748364) or (res == 214748364 and temp > 7):
return 0
res = res*10 + temp
new_x = new_x // 10
return res if x > 0 else -res
s = Solution()
print(s.int_reverse(123))
2. 回文数
给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。
# 方法1 整数反转与原数对比
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
new_x = x
sum = 0
while new_x != 0:
temp = new_x % 10
if (sum > 214748364) or (sum == 214748364 and temp > 7):
return False
sum = sum * 10 + temp
new_x = new_x // 10
if sum == x:
return True
return False
# 方法1的加更版,优化
class Solution:
def isPalindrome(self, x: int) -> bool:
if (x < 0) or (x % 10 == 0 and x != 0):
# x的末尾为0,同时x不等于0,此时的x是不可能对称的
return False
num = 0
while x > num:
num = num * 10 + x % 10
x //= 10
return (x == num) or (x == num // 10)
# 方法2--双指针更新
class Solution:
def isPalindrome(self, x: int) -> bool:
li = list(str(x))
left = 0
right = len(li)-1
while left < right:
if li[left] != li[right]:
return False
left += 1
right -= 1
return True
# 伪单指针
class Solution:
def isPalindrome(self, x: int) -> bool:
li = list(str(x))
left = 0
right = len(li) - 1
mid = (left + right) // 2
while left <= mid:
if li[left] != li[right-left]:
return False
left += 1
return True
# 方法3
# 从两边取中间
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
num = 0
div = 1
while x / div > 10:
div *= 10
while x != 0:
left = x // div
right = x % 10
if left != right:
return False
x = x % div // 10
div = div // 100
return True
方法4—Python优势
字符串的读取
class Solution:
def isPalindrome(self, x: int) -> bool:
s = str(x)
return s == s[::-1]