알고리즘 풀이/Codility

codility - Iterations (BinaryGap)

배게 2019. 12. 9. 18:39
728x90

1이 시작될 때 isCountable을 켜준다는 것 주의해주면됨 


나머지는 2진수 만들기, counting하기


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
36
37
38
39
40
    public int solution(int N) {
        // write your code in Java SE 8
        int answer = 0;
 
        System.out.println(N);
 
        String binary = decToBinary(N);
 
        System.out.println(binary);
 
        int count = 0;
        boolean isCountable = false;
        for (int i = 0; i < binary.length(); i++) {
            if (binary.charAt(i) == '1') {
                isCountable = true;
                if (count > answer)
                    answer = count;
                count = 0;
            }
            if (binary.charAt(i) == '0' && isCountable) {
                count++;
            }
        }
 
        return answer;
    }
 
    public String decToBinary(int N) {
        String str = "";
 
        int mod;
        while (N > 0) {
            mod = N % 2;
            N /= 2;
 
            str = Integer.toString(mod) + str;
        }
 
        return str;
    }
cs