본문 바로가기

코딩테스트/codility

BinaryGap

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

 

숫자를 이진수로 바꾸고

 

이진수로 바꿨을 때 1과 1사이에 존재하는 0의 갯수가 최대인 케이스를 찾아야 함

 

100000 처럼 0이 1로 둘러쌓여있지 않다면 0으로 계산된다는 제약이 있으며, 1111 처럼 0이 없어도 0이 됨.

 

주어진 숫자 N을 2로 나눠가며 직접 이진수로 변경해도 되고, Integer.toBinaryString을 사용해도 됨

class Solution {
    public int solution(int N) {
        
        // 숫자를 이진수로 변경하고, 각 자릿수로 분리
        char[] binary = Integer.toBinaryString(N).toCharArray();

        // 정답. 
        int maxGap = 0;

        // 1 사이에 들어있는 0의 갯수를 카운팅
        int gap = 0;
        for (int i = 0; i < binary.length; i++) {
            // 이진수 특성상 첫자리는 1이므로, 첫자리가 무엇인가에 대한 체크는 필요 없음
            if (binary[i] == '0') {
                gap++;
            } else {
            	// 0의 오른쪽 1을 만났을 때, 최대 gap 과 비교
                maxGap = Math.max(maxGap, gap);
                gap = 0;
            }
        }

        return maxGap;

    }
}

'코딩테스트 > codility' 카테고리의 다른 글

PermCheck  (0) 2023.09.29
TapeEquilibrium  (0) 2023.09.18
OddOccurrencesInArray  (0) 2023.09.16
CyclicRotation  (0) 2023.09.11
MaxDoubleSliceSum  (0) 2023.08.23