给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:
输入: 123
输出: 321
示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-integer
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
自己解答
class Solution:
def reverse(self, x: int) -> int:
res=0
if x<0:
x=-x
res =-int(str(x)[::-1])
else :
res =int(str(x)[::-1])
# print(res)
if -2147483648 <res and res < 2147483647:
return res
else:
return 0
执行用时:44 ms, 在所有 Python3 提交中击败了66.63% 的用户
内存消耗:13.5 MB, 在所有 Python3 提交中击败了5.16% 的用户
# 没什么技巧
大神解答
class Solution:
def reverse(self, x: int) -> int:
y, res = abs(x), 0
# 则其数值范围为 [−2^31, 2^31 − 1]
boundry = (1<<31) -1 if x>0 else 1<<31
while y != 0:
res = res*10 +y%10
if res > boundry :
return 0
y //=10
return res if x >0 else -res
执行用时:44 ms, 在所有 Python3 提交中击败了99.97% 的用户
内存消耗:13.3 MB, 在所有 Python3 提交中击败了81.26% 的用户
ps :
此代码为leetcode排名靠前的他人所写