868. Binary Gap
2018-07-18 本文已影响2人
fred_33c7
题目地址:https://leetcode.com/problems/binary-gap/description/
大意:找出二进制数中两个1的最大相间位数。
思路:一直右移,找出哪一次移动的位数最多。
class Solution:
def binaryGap(self, N):
"""
:type N: int
:rtype: int
"""
ret = 0
last_bit = None
bit = 0
while N:
if N & 1:
if last_bit is not None:
ret = max(ret, bit - last_bit)
last_bit = bit
N >>= 1
bit += 1
return ret
a = Solution()
print (a.binaryGap(5))