Input: 5
Output: 2
Explanation:
5 in binary is 0b101.
def binaryGap(self, N):
"""
:type N: int
:rtype: int
"""
s = bin(N)
num = 0
res = 0
for i in s:
if i == '1':
if res != 0:
num = max(res,num)
res = 1
else:
res += 1
elif res !=0:
res += 1
return num
当然也可以用位运算去比较,通过从后到前的每一位数对比1,然后直接相减。更巧妙:
def binaryGap(self, N):
A = [i for i in xrange(32) if (N >> i) & 1]
if len(A) < 2: return 0
return max(A[i+1] - A[i] for i in xrange(len(A) - 1))
网友评论