相关疑难解决方法(0)

Python:在整数的二进制表示中找到最长的二进制间隙

我想知道我的实施是否有效.我试图使用python找到解决该问题的最简单,最简单的解决方案.

def count_gap(x):
    """
        Perform Find the longest sequence of zeros between ones "gap" in binary representation of an integer

        Parameters
        ----------
        x : int
            input integer value

        Returns
        ----------
        max_gap : int
            the maximum gap length

    """
    try:
        # Convert int to binary
        b = "{0:b}".format(x)
        # Iterate from right to lift 
        # Start detecting gaps after fist "one"
        for i,j in enumerate(b[::-1]):
            if int(j) == 1:
                max_gap = max([len(i) for i in b[::-1][i:].split('1') if i])
                break
    except ValueError: …
Run Code Online (Sandbox Code Playgroud)

python python-3.x

5
推荐指数
3
解决办法
5068
查看次数

标签 统计

python ×1

python-3.x ×1