티스토리 뷰

https://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

이진법 사이에 있는 0의 개수를 구하면 된다.

1001이면 2

1000이면 0

1000101이면 3

으로 리턴하면 된다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
 
class Solution {
    public int solution(int[] A) {
 
        ArrayList<Integer> binaryNumList = new ArrayList<>();
 
        while(N > 0) {
            binaryNumList.add(N % 2);
            N /= 2;
        }
 
        int binaryNumListSize = binaryNumList.size();
        int cntBinaryGap = 0;
        int maxBinaryGap = 0;
 
        for(int i = binaryNumListSize - 1; i >= 0; i--) {
            if(binaryNumList.get(i) == 1) {
                maxBinaryGap = maxBinaryGap(cntBinaryGap, maxBinaryGap);
                cntBinaryGap = 0;
            } else {
                cntBinaryGap++;
            }
 
        }
        return maxBinaryGap;
    }
 
    private static int maxBinaryGap(int cnt, int max) {
        if(max < cnt) {
            return cnt;
        }
        return max;
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter

 

댓글