给定一个32位的有符号整数num,将num中的数字部分反转,最后返回反转的结果
1.只反转数字部分,符号位部分不反转
2.反转后整数num超过 32 位的有符号整数的范围 [−231, 231 − 1] ,返回 0
3.假设本题不允许存储 64 位整数(有符号或无符号,即C++不能使用long long ,Java不能使用long等)
数据范围:
-231 <= x <= 231-1
12
21
-123
-321
10
1
1147483649
0
class Solution: def reverse(self , x ): # write code here max32 = pow(2,31) min32 = -pow(2,31)-1 if(x>=0): str_x = str(x)[::-1] reversed_x = int(str_x) if reversed_x >= max32: return 0 else : return reversed_x if(x<0): str_x = str(abs(x))[::-1] reversed_x = int(str_x) if reversed_x > max32: return 0 else : return -reversed_x
# # # @param x int整型 # @return int整型 # import sys class Solution: def reverse(self , x ): # 判断值是否越界,对于Python3可不做此操作 # if x > sys.maxsize&nbs***bsp;x < -sys.maxsize -1: # return 0 res = 0 num = abs(x) while num: res = res*10 + num%10 num = int(num/10) if x>0: return res else: return -res
class Solution: def reverse(self , x ): # write code here flag = False if x == 0&nbs***bsp;x == -0: return x if x < 0: x = -x flag = True x = str(x) reverse_x = "" for i in range(len(x)): if reverse_x == "" and x[len(x)-i-1] == "0": continue reverse_x += x[len(x)-i-1] reverse_x = int(reverse_x) if flag: reverse_x = -reverse_x return reverse_x