본문 바로가기
Algorithm/Codility

Lesson 1: Iterations

by 꼬부기가우는소리 2016. 9. 2.
728x90


[Lesson 1: Iterations] 


Tasks 1. BinaryGap

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


사이트 : https://codility.com/programmers/task/binary_gap/

난이도 : PAINLESS

추가 자료 : Open reading material (PDF)




A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.


For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps.


Write a function:


int solution(int N);


that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.


For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5.


Assume that:

N is an integer within the range [1..2,147,483,647].


Complexity:

expected worst-case time complexity is O(log(N));

expected worst-case space complexity is O(1).




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def solution(N):
    max = 0
    gap = 0
    flag = False
 
    while N != 0:
        if N%2 == 1:
            if max < gap:    max = gap
            gap = 0
            flag = True
        else:
            if flag:
                gap += 1
        N = N/2
 
    return max
cs


주어진 양의 정수 N을 2로 반복적으로 나누어준다.

이 때, 2로 나눈 나머지가 1인 경우, 이제까지 구한 gap과 가장 큰 gap 값인 max와 비교하여 더 큰 쪽을 max에 저장시킨다.

만약 나머지가 1인 경우 gap의 값을 1씩 증가시킨다.


단, 구해진 값은 거꾸로 계산되는 것이기 때문에 (ex: 20의 이진값은 10100이지만 반대로 끝에서부터 계산되기 때문에 00101과 같은 순서로 나온다.) 처음 1이 나올 때까지 gap을 증가시키지 않는다.


모두 계산되어 N의 값이 0이 된 경우, max를 리턴시켜준다.



SCORE: 100%




'Algorithm > Codility' 카테고리의 다른 글

Lesson 3: Time Complexity  (0) 2016.09.02
Lesson 2: Arrays  (0) 2016.09.02

댓글