868. Binary Gap

题目地址: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))

所有题目解题方法和答案代码地址:https://github.com/fredfeng0326/LeetCode
    原文作者:fred_33c7
    原文地址: https://www.jianshu.com/p/be9a982e1a8d
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞