题目:
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123 Output: 321
Example 2:
Input: -123 Output: -321
Example 3:
Input: 120 Output: 21
解题思路:
假设我们正在处理一个只能存储32位有符号整数范围内的整数的环境:[−2^31,2^31 − 1]。 出于此问题的目的,假定您的函数在反向整数溢出时返回0。
""" 取x的符号的方法: 1.sigh = [-1,1](x<0) 2.x//abs(x) 不能计算0的情况 3.int((x+0.1)//abs(x+0.1)) 能计算0的情况 """
具体代码:
class Solution: #方法一 def reverse(self, x): """ :type x: int :rtype: int """ sign = [1,-1][x < 0] rst = sign * int(str(abs(x))[::-1]) return rst if -(2**31)-1 < rst < 2**31 else 0 #方法二 def reverse_better(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 if __name__ == '__main__': o = Solution() a = 123 b = o.reverse(x=a) print(b)