Leetcode #7. Reverse Integer
来源:互联网 发布:mac os 10.12原版镜像 编辑:程序博客网 时间:2024/05/29 18:14
class Solution: def reverse(self, x): """ :type x: int :rtype: int """ ret = 0 nega = 0 if x > 0 else 1 if nega: x = -x while x > 0: ret = ret * 10 + x % 10 x //= 10 if nega: ret = -ret if ret.bit_length() >= 32: return 0 return ret
注意
int.
bit_length
()Return the number of bits necessary to represent an integer in binary, excluding the sign and leading zeros:
More precisely, if x
is nonzero, then x.bit_length()
is the unique positive integer k
such that 2**(k-1) <= abs(x) < 2**k
. Equivalently, when abs(x)
is small enough to have a correctly rounded logarithm, then k = 1 + int(log(abs(x), 2))
. If x
is zero, then x.bit_length()
returns 0
.
去除符号位,共有31位,即当bit_length大于等于32时,超出32位int表示范围。
阅读全文