본문 바로가기

DEV/문제풀이

Lesson 1(Iterations) - Binary Gap

반응형

1. 문제 

 

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. The number 32 has binary representation 100000 and has no binary gaps.

Write a function:

class Solution { public 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. Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps.

Write an efficient algorithm for the following assumptions:

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

 

십진수 N이 주어지면 이진수로 변환하여 1사이의 0의 연속된 숫자의 최대값을 찾는 문제입니다. 

 

2.  소스

 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
class Solution {
    public int solution(int N) {
        // write your code in Java SE 8
        int res = 0;

        String binaryString = Integer.toBinaryString(N);
        
        int idx=0, preIdx=0;

        while(true){
           preIdx = idx;
            idx = binaryString.indexOf("1", idx);
                        
            if( idx == -1 ) break;
            
            if( idx - preIdx > res ) {
               res = idx - preIdx;
            }
            
            idx++;
        }

        return res;
    }
}

 

주어진 값을 2진화하여 문자열로 저장하여 1의 값을 찾습니다.

찾은 1의 위치와 이전의 1의 위치값을 계산하여 연속된 0의 수를 계산합니다.

 

* 다른 방법으로는 이진화 시키면서(입력값에서 2로 나눈 나머지를 계산) 카운트를 해도 됩니다.

 

3. 참고

 

레슨 1번 문제답게 쉬운 문제입니다.

십진수 32인 경우 이진화하면 10000으로 쌍이 되는 1이 없는 열린 상태입니다.

이럴 경우 0을 반환해야 되는 점을 주의하면 됩니다.

 

반응형

'DEV > 문제풀이' 카테고리의 다른 글

Lesson 2(Iterations) - OddOccurrencesInArray  (0) 2020.12.29
Codility  (0) 2020.12.26
Lesson 2(Iterations) - CyclicRotation  (0) 2020.12.25
Lesson6 - Distinct  (0) 2020.05.06
Lesson5 - MinAvgTwoSlice  (0) 2019.04.23
댓글