codility BinaryGap

Question:codility Lesson1 BinaryGap

My answer:

def solution(N):
    len_max = 0
    len_cur = 0
    flag    = 0
    Nstr = bin(N).replace('0b','')
    length = len(Nstr)

    for i in range(length):
        if Nstr[i] == '1':
            if flag == 0:
                flag = 1
            else:
                len_max = max(len_max,len_cur)
            len_cur = 0
        else:
            len_cur += 1
    return len_max
def solution(N):
    len_max = 0
    len_cur = 0
    flag    = 0
    mask    = 1
    length  = len(bin(N).replace('0b',''))

    for i in range(length):
        if ((N & (mask << i)) != 0):
            if flag == 0:
                flag = 1
            else:
                len_max = max(len_max,len_cur)
            len_cur = 0
        else:
            len_cur += 1
    return len_max

你可能感兴趣的:(python,codility)