LeetCode 7. 整数反转
-
难度:简单
-
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:
输入: 123
输出: 321
示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21
注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-integer
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
1. 判断是否大于0,然后判断转换后是否越界
2. 如果小于0,绝对值转换后要加-,也要判断越界
3. 整数转换可以转换成str,再取反
代码
class Solution:
def reverse(self, x: int) -> int:
if x>=0:
if int(str(x)[::-1])<=(2**31-1):
return int(str(x)[::-1])
else:
return 0
else:
if -int(str(abs(x))[::-1])>=-2**31:
return -int(str(abs(x))[::-1])
else:
return 0
-
优化一下
class Solution:
def reverse(self, x: int) -> int:
reverse_x = int(str(abs(x))[::-1])
result = reverse_x if x >=0 else -reverse_x
return result if (-2**31)<=result<=(2**31-1) else 0
最佳时间解法(供参考)
class Solution:
def reverse(self, x: int) -> int:
res = 0
news = abs(x)
while news!= 0:
temp = news % 10
res = res*10 + temp
news = news//10
if x<0:
if -res >= -2**31:
return -res
else:
return 0
else:
if res <= 2**31 - 1:
return res
else:
return 0
class Solution:
def reverse(self, x: int) -> int:
negative_flag = 1
if x < 0:
x = abs(x)
negative_flag = -1
res = tmp = 0
while x:
tmp = x % 10
x = x//10
res = res*10 + tmp
result = negative_flag*res
return result if -2**31 < result < 2**31-1 else 0
最佳内存解法(供参考)
class Solution:
def reverse(self, x: int) -> int:
if x > 0:
number_new = str(x)[::-1]
number_new = int(number_new.lstrip('0'))
elif x < 0:
number_new = str(-x)[::-1]
number_new = -int(number_new.lstrip('0'))
else:
number_new = 0
return 0 if (float(number_new) > 2147483647) or (float(number_new) < -2147483648) else number_new
class Solution:
def reverse(self, x: int) -> int:
tp_return = 0
new_str = ''
temp_str = str(x)
for x_letter in reversed(temp_str):
new_str = new_str + x_letter
if x >= 0:
tp_return = int(new_str)
else:
temp_num = int(new_str[:-1])
tp_return = (-temp_num)
if tp_return.bit_length() <= 31:
return tp_return
else:
return 0