LeetCode 868 Binary Gap 解题报告

题目要求

Given a positive integer N, find and return the longest distance between two consecutive 1's in the binary representation of N.

If there aren't two consecutive 1's, return 0.

题目分析及思路

给定一个正整数,返回该数二进制形式中连续两个1的最长间隔。若是没有连续的两个1,则返回0。可将该数转成二进制形式,得到的结果是个字符串,切片得到二进制形式。再以1进行分割。去掉结果列表的首尾元素,对剩余列表元素求长度并加1得到最后的间隔列表。若列表为空,则返回0;否则返回列表中的最大值。

python代码

class Solution:

    def binaryGap(self, N: int) -> int:

        dis = []

        b = bin(N)

        b = b[2:]

        gaps_str = b.split('1')

        gaps_str.pop()

        gaps_str.reverse()

        gaps_str.pop()

        gaps_int = [len(g)+1 for g in gaps_str]

        if not gaps_int:

            return 0

        else:

            return max(gaps_int)

        

猜你喜欢

转载自www.cnblogs.com/yao1996/p/10435389.html