美文网首页
868. Binary Gap

868. Binary Gap

作者: 腹黑君 | 来源:发表于2019-01-12 22:57 被阅读0次

    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))
    

    相关文章

      网友评论

          本文标题:868. Binary Gap

          本文链接:https://www.haomeiwen.com/subject/qjjhdqtx.html