본문 바로가기

Codility

[Lesson 1][Iterations] BinaryGap

app.codility.com/programmers/lessons/1-iterations/binary_gap/

 

BinaryGap coding task - Learn to Code - Codility

Find longest sequence of zeros in binary representation of an integer.

app.codility.com

# 2진수에서 1에 둘러싸인 0의 최대개수

def solution(N):
    max_v = 0
    cnt = 0
    flag = False
    while N:
        if N % 2 == 1:
            max_v = max(max_v, cnt)
            cnt = 0
            flag = True
        else:
            if flag:
                cnt += 1
        N //= 2

    return max_v


print(solution(9))    # 1011 => 2
print(solution(529))  # 1000010001 => 4
print(solution(20))   # 10100 => 1
print(solution(15))   # 1111 => 0
print(solution(32))   # 10000 => 0

'Codility' 카테고리의 다른 글

[Lesson 6][Sorting] Distinct  (0) 2021.05.07
[Lesson 5][Prefix Sums] CountDiv  (0) 2021.05.07
[Lesson 4][Counting Elements] FrogRiverOne  (0) 2021.05.07
[Lesson 3][Time Complexity] FrogJmp  (0) 2021.05.07
[Lesson 2][Arrays] CyclicRotation  (0) 2021.05.07