题目描述:
https://leetcode-cn.com/problems/reverse-integer/
题解:
<1>x=abs(x),将负数转为正数 <2>通过在一个while循环中,除10和余10的操作,从各位开始提取x的每个数位,写入nums数组 <3>将nums数组转为证书res <4>判断res是否越界,并使res保持与x符号一致 def reverse(self, x): weight2 = 1 nums = [] if x>0: flag = 1 else: flag = 0 x = abs(x) while x != 0: tmp = x % 10 x = int(x / 10) nums.append(tmp) res = 0 for i in range(len(nums) - 1, -1, -1): res = res + nums[i] * weight2 weight2 = weight2 * 10 if res>2**31-1 or res<-2**31-1: return 0 if flag==1: return res else: return -res